Hand Out Cookies
Problem
Each child has a smallest cookie size that will make them happy, and each cookie has a size. A child gets at most one cookie and a cookie goes to at most one child. Return the largest number of children you can make happy.
Examples
Input: wants = [1, 2, 3], sizes = [1, 1]
Output: 1
Why: both cookies only satisfy the child who wants size 1
Input: wants = [1, 2], sizes = [1, 2, 3]
Output: 2
Input: wants = [5], sizes = []
Output: 0
Why: edge case, no cookies means no happy children
Hints
0 / 3
Handing the biggest cookie to whoever asks first can waste it on a child a small cookie would have satisfied. Think about which child each cookie should go to.
Sort both lists. The least demanding child is the easiest to please, and the smallest cookie that pleases them is the cheapest way to do it.
Walk the cookies from smallest to largest with a pointer on the sorted children. If the current cookie is big enough for the least demanding child still waiting, give it to them and move the pointer; otherwise the cookie is too small for everyone left, so skip it.
Solution
After sorting, the least demanding waiting child is the one most worth serving, and the smallest cookie that satisfies them is the one whose use costs the least; an exchange argument shows that swapping any optimal assignment towards this choice never loses a happy child. A cookie too small for the least demanding waiting child is too small for everyone after them too, so it is discarded. One pass over the cookies with a pointer into the children does the rest. Time is O(n log n + m log m) for the sorts, and space is O(1) beyond them.
def happy_children(wants, sizes):
wants, sizes = sorted(wants), sorted(sizes)
child = 0 # least demanding child still waiting
for s in sizes: # smallest cookie first
if child < len(wants) and s >= wants[child]:
child += 1 # this cookie is enough, hand it over
return child
print(happy_children([1, 2, 3], [1, 1])) # -> 1
print(happy_children([1, 2], [1, 2, 3])) # -> 2
print(happy_children([5], [])) # -> 0Stuck on the idea rather than the code? What Makes Greedy Work covers it.