Assign Cookies
Easy
GreedySorting
Problem
Children have greed factors g[i]; cookies have sizes s[j]. A child is content if a cookie of size ≥ greed is assigned. Maximise content children.
Example 1
Input: g=[1,2,3], s=[1,1]
Output: 1
Example 2
Input: g=[1,2], s=[1,2,3]
Output: 2
Constraints
- 1 ≤ g.length, s.length ≤ 3·10⁴
Approach — Greedy
This is a Greedy problem. The idea: make the locally best choice at each step, which provably builds up to the global optimum here. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n log n) time.
Solution code
Python
class Solution:
def findContentChildren(self, g, s):
g.sort()
s.sort()
i = j = 0
while i < len(g) and j < len(s):
if s[j] >= g[i]:
i += 1
j += 1
return i
Java
import java.util.*;
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int i = 0, j = 0, count = 0;
while (i < g.length && j < s.length) {
if (s[j] >= g[i]) { count++; i++; }
j++;
}
return count;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Assign Cookies interactively → ← All solutions