Fair Distribution of Cookies

Hand out bags of cookies to children so that the child with the most cookies gets as few as possible.

There are n bags of cookies, where cookies[i] is the number of cookies in bag i, and k children. Every bag goes to exactly one child, and a bag cannot be split. The unfairness of a distribution is the largest number of cookies any one child receives. Return the smallest unfairness possible. The limits are 2 <= k <= n <= 8.

Example 1
Input: cookies = [8, 15, 10, 20, 8], k = 2
Output: 31
Explanation: one child gets 8 + 15 + 8 = 31, the other 10 + 20 = 30.
Example 2
Input: cookies = [6, 1, 3, 2, 2, 4, 1, 2], k = 3
Output: 7
Explanation: for example [6, 1], [3, 2, 2] and [4, 1, 2], which sum to 7, 7 and 7.
Solution

The Idea

Picture five sealed bags of cookies on a table, holding 8, 15, 10, 20 and 8 cookies, and two children waiting for them. Each bag goes whole to one child. Whoever ends up with the most cookies sets the unfairness, and you want that number as low as you can get it.

The five bags hold 61 cookies together. A perfectly even split would give each child 30.5, and cookies come whole, so one of them must get at least 31. Example 1 reaches exactly that: 8 + 15 + 8 = 31 for one child and 10 + 20 = 30 for the other. Example 2 works out evenly too: 21 cookies for three children, and the split in its explanation gives each child 7.

An even split is not always possible, though. With bags of 1, 1, 1 and 100 for two children, the child who gets the bag of 100 has 100 cookies whatever happens to the rest. So the answer cannot be read off the total, and has to come from trying hand-outs. How many are there? Number the children 0 and 1. Each of the five bags can go to either child, which makes 25 = 32 hand-outs. With 8 bags and 8 children it would be 88 = 16,777,216.

Can most of them be skipped? Build each hand-out one bag at a time, and keep each child's running total of cookies, called the child's share. Look at the picture below. Each box shows the two shares as "child 0 | child 1", and each line down gives the next bag to one child.

Part of the choice tree for bags 8, 15, 10, 20, 8 and two children. Giving bag 8 to child 1 is skipped as a mirror of 8 | 0. Below 23 | 0 a complete hand-out 31 | 30 sets best = 31. Below 18 | 15, giving bag 20 makes 38 | 15 or 18 | 35, and both are cut.

The boxes and lines form a tree of choices. The search goes down one branch to the bottom, then steps back up, takes the last bag back from its child, and tries the next child. Taking a bag back from one child so it can go to the next child is called backtracking.

Two things in the picture save work. First, the dashed box "0 | 8" is never visited. Giving the first bag to child 1 instead of child 0 only swaps the children's names, so every hand-out below it mirrors one below "8 | 0".

Second, the search always tries child 0 first, which is the left branch in the picture. Below "23 | 0" it reaches the complete hand-out "31 | 30", after four worse hand-outs with unfairness 61, 53, 41 and 33, so the best unfairness so far is 31. Now look at "18 | 15". Giving bag 20 to either child makes a share of 38 or 35. A share never shrinks when more bags come, so neither branch can end below 31, and both are cut on the spot, in the orange boxes.

So the search still tries hand-outs bag by bag. It drops a branch as soon as its largest share reaches the best complete answer, and it never tries two children who both have nothing yet for the same bag.

Solution Approach

Turning the choice tree into code means settling three things: how to hand out one bag at a time, when to cut a branch, and how to skip mirrored hand-outs. Each cut is measured against a plain search that tries everything.

Handing out one bag at a time

How can the code try every hand-out without one loop per bag? A method assign takes the number of the next bag to give out. It loops over the children, adds the bag to that child's entry in an array share, and calls itself for the following bag. When that call returns, it subtracts the bag again, so the next child in the loop starts from the same shares.

Run with no cuts at all, this visits the whole tree. For Example 1 that is 63 calls of assign and all 32 complete hand-outs. For Example 2, with eight bags and three children, it is 9,841 calls and 38 = 6,561 complete hand-outs.

Cutting branches that cannot win

How does the code know a branch cannot win? It keeps two numbers. best is the smallest unfairness among the complete hand-outs found so far. currentMax is the largest share on the current branch, passed down to each call so it never has to be worked out again.

If currentMax is already at least best, the call returns at once. Equal is enough to stop, because a branch that ties best cannot improve on it. In Example 2, this check alone brings the 9,841 calls down to 370.

Skipping children who have nothing yet

Which children are mirrors of each other? Two children who both have nothing yet. Giving the bag to either of them leads to the same hand-outs with the names swapped. The loop tries children in order, and a bag only reaches child 1 after child 0 has cookies, so the empty children always come last.

So after trying a child whose share was 0 before this bag, the loop stops with break. That is why the first bag, the 8 at the top of the picture, only ever goes to child 0. With both cuts, Example 1 takes 24 calls, of which 7 are cut, and Example 2 takes 130 calls instead of 9,841.

Java Solution

The method distributeCookies and its helper assign work in these steps:

  1. First, distributeCookies sets the static field best to Integer.MAX_VALUE, so the first complete hand-out beats it. It then calls assign with bag 0, a new array share of k zeros, and a currentMax of 0.
  2. Each call of assign first compares currentMax with best and returns if it is not smaller.
  3. If bag equals cookies.length, every bag has been given out, and the check above already showed this hand-out is better, so best becomes currentMax.
  4. Otherwise a loop over child adds cookies[bag] to share[child], calls assign for bag + 1 with Math.max(currentMax, share[child]), and then subtracts the bag again.
  5. After the subtraction, if share[child] is 0, that child had nothing before this bag, so the loop ends with break.
  6. When the search is done, distributeCookies returns best.

The main method runs both examples, three bags for three children, a bag of 100 next to three bags of 1, and four equal bags of 4 for two children.

Java
public class FairDistributionOfCookies {

    private static int best;

    public static int distributeCookies(int[] cookies, int k) {
        best = Integer.MAX_VALUE;
        assign(cookies, 0, new int[k], 0);
        return best;
    }

    // Give bag number 'bag' to each child in turn; 'currentMax' is the largest share so far
    private static void assign(int[] cookies, int bag, int[] share, int currentMax) {
        if (currentMax >= best) {
            return;                              // already no better than a known answer
        }
        if (bag == cookies.length) {
            best = currentMax;                   // every bag given out, and this is better
            return;
        }
        for (int child = 0; child < share.length; child++) {
            share[child] += cookies[bag];
            assign(cookies, bag + 1, share, Math.max(currentMax, share[child]));
            share[child] -= cookies[bag];
            if (share[child] == 0) {
                break;                           // other empty children would repeat this case
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(distributeCookies(new int[] {8, 15, 10, 20, 8}, 2));
        System.out.println(distributeCookies(new int[] {6, 1, 3, 2, 2, 4, 1, 2}, 3));
        System.out.println(distributeCookies(new int[] {5, 3, 9}, 3));
        System.out.println(distributeCookies(new int[] {1, 1, 1, 100}, 2));
        System.out.println(distributeCookies(new int[] {4, 4, 4, 4}, 2));
    }
}

Running it prints:

Output
31
7
9
100
8

31 and 7 match the two examples. The 9 comes from three bags for three children: each child gets one bag, and the bag of 9 sets the unfairness. The 100 is the uneven case from the bags of 1, 1, 1 and 100. The other child gets all three small bags, but the child with the bag of 100 still holds 100. The last line, 8, is two bags of 4 for each child.

Complexity

The running time is the number of calls of assign, and the memory is the share array plus the chain of calls that are still open.

  • Time: O(kn), because each of the n bags can go to any of the k children, so a search without cuts reaches kn complete hand-outs. The two cuts remove most of them in practice, 130 calls instead of 9,841 for Example 2, but O(kn) stays the upper bound.
  • Space: O(k + n), because share holds one total per child, and the open calls of assign are at most n + 1 deep, one per bag plus the call that finds every bag given out.