The Assign Cookies problem involves distributing cookies to children such that the maximum number of children are satisfied. Each child has a greed factor, and each cookie has a size. A child is satisfied if the size of the cookie is greater than or equal to their greed factor.
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g); // Sort greed factors
Arrays.sort(s); // Sort cookie sizes
int child = 0, cookie = 0;
while (child < g.length && cookie < s.length) {
if (s[cookie] >= g[child]) {
child++; // Satisfy this child
}
cookie++; // Move to the next cookie
}
return child; // Number of satisfied children
}
}
O(M log M + N log N)
, where M
is the number of children and N
is the number of cookies.O(min(M, N))
, for iterating through the arrays.O(M log M + N log N)
.Input: g = [1,2,3], s = [1,1]
Output: 1
Explanation:
- Only 1 child can be satisfied with the given cookies.