Assign Cookies - Problem
You're a parent who wants to make your children happy by giving them cookies! ๐ช But there's a catch - you can only give each child at most one cookie.
Here's the situation:
- Each child
ihas a greed factorg[i]- the minimum size cookie they'll be satisfied with - Each cookie
jhas a sizes[j] - A child
iwill be content if they receive a cookie wheres[j] >= g[i]
Your goal: Maximize the number of content children by optimally assigning cookies.
Example: If you have children with greed factors [1, 2, 3] and cookies with sizes [1, 1], you can only satisfy 2 children (those with greed factors 1 and 2) by giving them the cookies of size 1 each.
Input & Output
example_1.py โ Basic Case
$
Input:
g = [1,2,3], s = [1,1]
โบ
Output:
1
๐ก Note:
You have 3 children with greed factors 1, 2, 3 and 2 cookies of size 1. Only one child (with greed factor 1) can be satisfied.
example_2.py โ Perfect Match
$
Input:
g = [1,2], s = [1,2,3]
โบ
Output:
2
๐ก Note:
Both children can be satisfied. Child with greed 1 gets cookie of size 1, child with greed 2 gets cookie of size 2.
example_3.py โ No Satisfaction Possible
$
Input:
g = [5,6], s = [1,2,3]
โบ
Output:
0
๐ก Note:
All children have greed factors larger than any available cookie size. No child can be satisfied.
Visualization
Tap to expand
Understanding the Visualization
1
Line up children by greed
Arrange children from least picky to most picky
2
Sort cookies by size
Arrange cookies from smallest to largest
3
Use greedy strategy
Give the smallest acceptable cookie to each child
4
Maximize happiness
This approach ensures maximum number of satisfied children
Key Takeaway
๐ฏ Key Insight: The greedy approach works because satisfying the least demanding child first with the smallest possible cookie preserves larger cookies for more demanding children later.
Time & Space Complexity
Time Complexity
O(2^(m+n))
For each child-cookie pair, we have multiple choices leading to exponential combinations
โ Linear Growth
Space Complexity
O(n)
Recursion depth can go up to n children
โก Linearithmic Space
Constraints
- 1 โค g.length โค 3 ร 104
- 0 โค s.length โค 3 ร 104
- 1 โค g[i] โค 231 - 1
- 1 โค s[j] โค 231 - 1
- Each child can receive at most one cookie
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code