Assign cookies
Easy TimeO(n log n) SpaceO(n)
Each child will only be content with a cookie of at least a certain size, given in greed, and each cookie has a size in cookies. A child gets at most one cookie, and each cookie may be given away only once; a cookie smaller than a child's greed factor contents nobody. Neither list is sorted. Return the largest number of children that can be made content.
Examples
Example 1
- Input
- greed = [1, 2, 3]cookies = [1, 1, 2, 3]
- Output
- The
31takes a1, the2takes the2, the3takes the3— one cookie left over.
Example 2
- Input
- greed = [1, 2]cookies = [1, 1]
- Output
- Both cookies are size 1, so the child wanting 2 cannot be contented and only one is.
1
The Code
function findContentChildren(greed, cookies) {
const g = greed.slice().sort((a, b) => a - b);
const s = cookies.slice().sort((a, b) => a - b);
let child = 0;
let cookie = 0;
while (child < g.length && cookie < s.length) {
if (s[cookie] >= g[child]) {
child++;
}
cookie++;
}
return child;
}
findContentChildren([1, 2, 3], [1, 1, 2, 3]);Done