#455

Assign Cookies

Easy Sort + match smallest

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Each child needs a cookie of at least their greed size; each cookie has a size and goes to at most one child. Maximise the number of content children.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: feed as many children as possible.

Why this works: give each child the smallest cookie that is big enough, so the big cookies are saved for greedier kids.

Example: greed [1, 2, 3], cookies [1, 1]

child 1 gets cookie 1child 2: remaining cookie 1 too small → 1 content child

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Giving the biggest cookie to the first child — it might be needed for a greedier child.

Solve on LeetCode ↗
Complexity
  • Time: O(n log n + m log m).
  • Space: O(1) besides sorting.
Topic: Greedy
🎬 Episodes 69–73: video coming soon