455. Assign Cookies
Problem
Child i is content with a cookie of size at least g[i]; cookie j has size s[j]. Each child gets at most one cookie. Return the maximum number of content children.
Example: g = [1,2,3], s = [1,1] → 1; g = [1,2], s = [1,2,3] → 2
Sort both. Give the smallest cookie that satisfies the least greedy child; a cookie too small for this child is too small for everyone after.
Complexity: O(n log n).
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort(); s.sort()
child = 0
for size in s:
if child < len(g) and size >= g[child]:
child += 1
return child
assert Solution().findContentChildren([1, 2, 3], [1, 1]) == 1
assert Solution().findContentChildren([1, 2], [1, 2, 3]) == 2
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g); Arrays.sort(s);
int child = 0;
for (int size : s) if (child < g.length && size >= g[child]) child++;
return child;
}
}
func findContentChildren(g []int, s []int) int {
sort.Ints(g)
sort.Ints(s)
child := 0
for _, size := range s { // each cookie goes to the least greedy child it satisfies
if child < len(g) && size >= g[child] {
child++
}
}
return child
}