Graph Theory37 sections · 1633 units
Open in Course

Assign Cookies - Greedy Solution

(Two pointers)

The greedy approach: sort children by greed factor, sort cookies by size. For each child in order, give them the smallest cookie that satisfies their greed. This is O(nlogn)O(n \log n) and simpler than matching. Why does greedy work?

If you give a child a larger cookie than needed, you might waste it. The smallest valid cookie is always the right choice because it preserves larger cookies for greedier children.

Space complexity is O(V)O(V) for the data structures used.