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
3
The 1 takes a 1, the 2 takes the 2, the 3 takes the 3 — one cookie left over.

Example 2

Input
greed = [1, 2]cookies = [1, 1]
Output
1
Both cookies are size 1, so the child wanting 2 cannot be contented and only one is.

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
Step through findContentChildren([1, 2, 3], [1, 1, 2, 3]) call by call