Introduction
Assign Cookies is one of the easiest Greedy Algorithm problems.
You are given:
- g[i] = greed factor of child
- s[i] = size of cookie
Goal:
Maximize the number of satisfied children.
Condition:
cookie size >= greed factor Example
Input
g = [1,2,3]s = [1,1]Output
1Explanation
Child 1 gets cookie 1Satisfied = 1
Child 2 and Child 3 cannot be satisfied.Key Observation
Give the smallest possible cookie to the least greedy child.
Sorting helps make optimal assignments.
Algorithm
- Sort greed array.
- Sort cookie array.
- Use two pointers.
- If cookie satisfies child:
- Assign cookie.
- Move both pointers.
- Otherwise:
- Try larger cookie.
- Count satisfied children.
Dry Run
Input
g = [1,2,3]s = [1,1]Sort Arrays
g = [1,2,3]s = [1,1]First Cookie
1 satisfies child 1Satisfied
1Second Cookie
1 cannot satisfy child 2 Answer
1Approach : Greedy
Always assign the smallest available cookie that can satisfy the current child.
This prevents wasting larger cookies on smaller greed factors.