progress

~/problems / Greedy

Feed the most children

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Each child has an appetite need[i], and each snack a size snacks[j]. A child is happy with one snack at least as big as their appetite. Each snack feeds at most one child.

Write max_happy(need: list[int], snacks: list[int]) -> int: the most children you can make happy.

max_happy([1, 2, 3], [1, 1])      # 1   (only the child with need 1 can be fed)
max_happy([4, 1, 2], [3, 1, 5])   # 3   (1 gets 1, 2 gets 3, 4 gets 5)
max_happy([5], [])                # 0

Up to 10^5 children and 10^5 snacks, sizes 1 to 10^9.

⭐ Bonus: a speed test with 100,000 of each earns a star in O(n log n).

Show hint

sort both lists and walk them with two pointers, giving each child (smallest appetite first) the smallest snack that is big enough. A snack too small for this child is too small for every later one.

Topic: Greedy with sorting. Sort, then take the locally best choice; prove it with an exchange argument.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc