LeetCode 455: Assign Cookies Solution
Master LeetCode problem 455 (Assign Cookies), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
455. Assign Cookies
Problem Explanation
Explanation
To solve this problem, we can first sort both the greed factor array g and the cookie size array s in ascending order. Then, we can iterate through the arrays and assign cookies to children starting from the child with the lowest greed factor and the smallest cookie size. If the current cookie size is sufficient for the current child, we assign the cookie to the child and move on to the next child and cookie. If the cookie size is not sufficient, we move to the next available cookie. By doing this, we can maximize the number of content children.
Time complexity: O(n log n) - sorting both arrays takes O(n log n) time
Space complexity: O(1) - we are not using any extra space except for a few variables
Solution Code
import java.util.Arrays;
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int i = 0; // pointer for greed factor array
int j = 0; // pointer for cookie size array
int contentChildren = 0;
while (i < g.length && j < s.length) {
if (s[j] >= g[i]) {
contentChildren++;
i++;
}
j++;
}
return contentChildren;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 455 (Assign Cookies)?
This page provides optimized solutions for LeetCode problem 455 (Assign Cookies) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 455 (Assign Cookies)?
The time complexity for LeetCode 455 (Assign Cookies) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 455 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 455 in Java, C++, or Python.