What is Assign Cookies
Each child has a greed factor g[i], the minimum cookie size that makes that child content. Each cookie has a size s[j]. A child receives at most one cookie, and a cookie goes to at most one child. Return the maximum number of content children.
Example 1. The cookie of size 1 feeds the child of greed 1. The other cookie is also 1, so the children of greed 2 and 3 stay hungry.
greed = 1 2 3 cookies = 1 1 Output: 1
Example 2. After sorting, cookie 1 feeds greed 1 and cookie 2 feeds greed 2. Cookie 3 is left over.
greed = 1 2 cookies = 1 2 3 Output: 2
Approach
Interactive visualization
The walk starts on the first pseudocode line. Next and Play move one step at a time, and the highlighted line is the line that just ran.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n log n) | Sorting dominates. The two pointers then walk each row once. |
| Space | O(1) | Extra memory is the two pointers, aside from the sort. |
| Greedy choice | Smallest fit | A cookie too small for this child is useless later. A larger cookie should be saved. |
Implementation