Greedy Algorithms8 sections · 316 units
Open in Course

Assign Cookies - The Idea

Match smallest to smallest

The insight: sort both arrays. Then match the smallest cookie to the smallest satisfiable child. Why? If a small cookie can satisfy a child, using a larger cookie wastes capacity. Larger cookies should be saved for greedier children.

More formally: if cookie jj can satisfy child ii, any larger cookie can too. Using the smallest sufficient cookie leaves more options for harder children. The sort order is the core idea. If you sorted descending instead of ascending, greedy would fail. Choosing the right sort is what makes greedy work.