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 ncookies[i]ik2 <= k <= n <= 8
Example 1
Output: 31
Explanation: one child gets 8 + 15 + 8 = 31, the other 10 + 20 = 30.
Example 2
Output: 7
Explanation: for example [6, 1], [3, 2, 2] and [4, 1, 2], which sum to 7, 7 and 7.
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.
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 assignshare
Run with no cuts at all, this visits the whole tree. For Example 1 that is 63 calls of assign
Cutting branches that cannot win
How does the code know a branch cannot win? It keeps two numbers. bestcurrentMax
If currentMaxbestbest
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
Java Solution
The method distributeCookiesassign
- First,
sets the static fielddistributeCookies tobest , so the first complete hand-out beats it. It then callsInteger.MAX_VALUE with bag 0, a new arrayassign ofshare zeros, and ak of 0.currentMax - Each call of
first comparesassign withcurrentMax and returns if it is not smaller.best - If
equalsbag , every bag has been given out, and the check above already showed this hand-out is better, socookies.length becomesbest .currentMax - Otherwise a loop over
addschild tocookies[bag] , callsshare[child] forassign withbag + 1 , and then subtracts the bag again.Math.max(currentMax, share[child]) - After the subtraction, if
is 0, that child had nothing before this bag, so the loop ends withshare[child] .break - When the search is done,
returnsdistributeCookies .best
The main
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:
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 assignshare
- 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
holds one total per child, and the open calls ofshare are at most n + 1 deep, one per bag plus the call that finds every bag given out.assign