Greedy Algorithms8 sections · 316 units
Open in Course

Assign Cookies - Implementation

The code

Here is the complete solution:

function findContentChildren(greed, cookies)
 sort greed in ascending order
 sort cookies in ascending order
 child := 0
 cookie := 0
 while child < length of greed and cookie < length of cookies
 if cookies[cookie] >= greed[child] then
 child := child + 1
 cookie := cookie + 1
 return child

Time: O(nlogn+mlogm)O(n \log n + m \log m) for sorting. Space: O(1)O(1) extra (or O(n+m)O(n + m) if sorting creates copies).