Assign Cookies

Give each child at most one cookie that is big enough, and make as many children content as possible.

Some children are waiting for cookies. Each child has a number called a greed factor: the child in position i is content only with a cookie of size at least g[i]. The cookie in position j has size s[j]. Each child gets at most one cookie, and each cookie goes to at most one child. Return the largest number of children that can be made content.

Example 1
Input: g = [1, 2, 3], s = [1, 1]
Output: 1
Explanation: both cookies have size 1, which is enough only for the child with greed factor 1.
Example 2
Input: g = [1, 2], s = [1, 2, 3]
Output: 2
Explanation: the cookie of size 1 goes to the child with greed factor 1, and the cookie of size 2 to the child with greed factor 2.
Solution

The Idea

Picture four children with greed factors 3, 1, 5 and 2, and four cookies of sizes 2, 1, 4 and 1. The child with greed 3 is happy with a cookie of size 3 or more and turns down anything smaller. How many of the four children can go away happy?

Handing the cookies out carelessly can waste one. Give the size 4 cookie to the child with greed 1, and that child is content, but now no cookie left is big enough for the child with greed 3. A size 1 cookie would have done for greed 1. So the real question is which cookie each child should get, so that the big cookies stay with the children who need them.

Line both groups up from small to large: the children by greed, 1, 2, 3, 5, and the cookies by size, 1, 1, 2, 4. Then walk along the cookies, keeping track of the least greedy child who is still waiting. Look at the picture below.

Children sorted by greed 1, 2, 3, 5 and cookies sorted by size 1, 1, 2, 4. The first size 1 cookie goes to greed 1. The second size 1 cookie is skipped, too small for greed 2. Size 2 goes to greed 2, size 4 to greed 3, and greed 5 has no cookie left.

The first cookie, size 1, is enough for greed 1, and the arrow shows that child getting it. The next cookie is also size 1, too small for greed 2, the least greedy child still waiting. Every other waiting child is greedier still, so the picture marks it "skipped: too small for greed 2". Size 2 then goes to greed 2 and size 4 to greed 3. The child with greed 5 is labelled "no cookie left", and the answer is 3.

At each step the walk takes the choice that looks best right now, the smallest cookie that pleases the easiest child to please, and never goes back to change it. Handing out the cookies one sure match at a time like this is called a greedy choice. Here it pays off because a cookie that is enough for one child is also enough for any less greedy child, so keeping the bigger cookies back never hurts.

Solution Approach

Turning that idea into code means settling three things: why the greedy choice is safe compared with trying every matching, how to walk the two arrays, and when to stop.

Why the greedy choice is safe

Could some other way of handing out the cookies make more children content? Trying every matching would settle it, but with 10 children and 10 cookies there are already 3,628,800 ways to give each child a different cookie, and with 20 of each there are more than 1018.

Instead, take any best matching and look at the least greedy child. If that child holds a bigger cookie than the smallest one that is enough, swap the two. If another child held the small cookie, that child now gets the bigger one, which is still enough. If the child had no cookie, give it the small one: at most one other child loses it, so the count of content children does not drop either way.

Walking the two sorted arrays

How do we find the smallest cookie that is enough without searching all the cookies each time? Sort the greed factors and the cookie sizes. One index, child, points at the least greedy child still waiting, and another, cookie, moves along the sizes from small to large.

If the cookie at cookie is enough, that child is content and child moves on. If it is not, the cookie is too small for every child still waiting, because they are all at least as greedy, so it is skipped. Without the sorts this walk goes wrong: for g = [3, 1] and s = [1, 3] it compares size 1 with greed 3, skips that cookie, and returns 1 instead of 2.

When to stop

When is the walk over? It ends when the cookies run out or every child is content. By then child has moved once for each content child, so its value is the answer itself.

Java Solution

The method findContentChildren works in these steps:

  1. First, sort both arrays with Arrays.sort(g) and Arrays.sort(s), so the least greedy child and the smallest cookie come first.
  2. Set child to 0. It points at the least greedy child still waiting, and it also counts the content children.
  3. Walk the cookies with one loop, moving cookie from the smallest size up. The loop stops when the cookies run out or child reaches g.length, which means every child is content.
  4. Inside the loop, if s[cookie] >= g[child], the cookie is enough, so add 1 to child. Otherwise the loop simply moves on to the next cookie.
  5. When the loop ends, return child, the number of content children.

The main method runs both examples, the children and cookies from the picture (printing g after the call), a call with no cookies, and g = [3, 1] with s = [1, 3], given out of order.

Java
import java.util.Arrays;

public class AssignCookies {

    public static int findContentChildren(int[] g, int[] s) {
        Arrays.sort(g);                       // greed factors, least greedy first
        Arrays.sort(s);                       // cookie sizes, smallest first
        int child = 0;
        for (int cookie = 0; cookie < s.length && child < g.length; cookie++) {
            if (s[cookie] >= g[child]) {
                child++;                      // big enough: this child is content
            }                                 // too small: skip the cookie
        }
        return child;
    }

    public static void main(String[] args) {
        System.out.println(findContentChildren(new int[] {1, 2, 3}, new int[] {1, 1}));
        System.out.println(findContentChildren(new int[] {1, 2}, new int[] {1, 2, 3}));
        int[] g = {3, 1, 5, 2};
        int[] s = {2, 1, 4, 1};
        System.out.println(findContentChildren(g, s));
        System.out.println("g after the call: " + Arrays.toString(g));
        System.out.println(findContentChildren(new int[] {1, 2}, new int[] {}));
        System.out.println(findContentChildren(new int[] {3, 1}, new int[] {1, 3}));
    }
}

Running it prints:

Output
1
2
3
g after the call: [1, 2, 3, 5]
0
2

Example 1 prints 1 and Example 2 prints 2. The 3 on the third line is the answer from the picture, and the next line shows a side effect: g was [3, 1, 5, 2] and now reads [1, 2, 3, 5]. Arrays.sort sorts the caller's array in place, so copy the arrays first if their old order still matters.

With no cookies, the loop never runs and the method returns 0. The last line, 2, comes from g = [3, 1] and s = [1, 3], where the walk without sorting returns 1.

Complexity

The two sorts cost the most; the walk after them is a single pass over the cookies.

  • Time: O(n log n + m log m), because sorting the n greed factors and the m cookie sizes takes that long, and the walk then moves cookie forward at most m times.
  • Space: O(log n + log m), because the method keeps only the two indexes, and Arrays.sort on an int array uses a quicksort whose call stack grows about that deep.

Matching the smallest item that fits is also the greedy step in Boats to Save People.