Candy Distribution
Hand out the fewest candies to a line of children when a higher rating must get more than its neighbour.
Some children stand in a line, and each one has a rating, given in the array ratings
Example 1
Output: 5
Explanation: the children get 2, 1 and 2 candies.
Example 2
Output: 4
Explanation: the children get 1, 2 and 1 candies. Equal ratings set no rule between them, so the third child can get 1.
The Idea
Think of a teacher rewarding a row of children after a game. Every child gets something, and a child rated higher than the child next to them must get more. The teacher also wants to buy as few candies as possible.
Try Example 1 the simple way: give each of the three children one candy. The middle child is rated 0, lower than both neighbours, so one candy is fine. The first child is rated 1, higher than the 0 beside them, so they need at least 2. The last child, rated 2, is also higher than the 0 and needs 2 as well. That makes 2 + 1 + 2 = 5.
In Example 2, the last two children are both rated 2. Equal ratings set no rule, so the last child keeps 1 candy, and the total is 1 + 2 + 1 = 4.
In a short line, each child only looks at the child next to them. In a longer line, a child's count can depend on children further away. Take the ratings 1, 3, 5, 4, 2, 1. Coming from the left end, the ratings rise 1, 3, 5. The child rated 5 must beat the child rated 3, who must beat the child rated 1, so the child rated 5 needs at least 3 candies. Coming from the right end, the ratings rise 1, 2, 4, 5, which asks for at least 4. So how many does the child rated 5 really need?
Look at the picture below. The bars at the top are the ratings, and each row underneath has one box per child.
In the blue row, each box holds the climb from the left: how many children, ending at this one, form an unbroken run of rising ratings coming from the left end. A child rated higher than the left neighbour gets one more than that neighbour, and any other child starts again at 1. The teal row holds the climb from the right, counted the same way from the right end. The child rated 5, in orange, needs 3 for the rule on the left and 4 for the rule on the right, and 4 meets both.
So every child needs the larger of two numbers: their climb from the left and their climb from the right. The bottom row takes the larger number for each child, 1, 2, 4, 3, 2, 1, which adds up to 13. One walk along the line in each direction is enough to find both numbers.
Solution Approach
Turning that idea into code means settling three things: how to count the climb from the left, how to add the climb from the right, and why the total that comes out is the smallest possible.
Fixing one child at a time
Why not give everyone one candy, then fix broken rules until none are left? That works, but slowly, because a fix can break a rule one child further along. Take the falling line 5, 4, 3, 2, 1, swept from left to right again and again.
In each sweep, a child rated higher than the right neighbour is raised to one more than that neighbour has at that moment. The neighbour may be raised later in the same sweep, so the correct counts creep back from the right end by one child per sweep. It takes four sweeps that change something and a fifth to see that nothing is broken. That is about one sweep per child, so a line of n children costs about n × n checks.
Counting the climb from the left
How can one walk count the climb from the left for every child? Keep one number per child in an array candies
Adding the climb from the right
What about the rule on the right? The same walk, from the right end back to the left, counts that climb. Instead of keeping it in a second array, this walk writes straight into candies
Why the larger, and not simply the new count? Take the line 1, 3, 4, 5, 2. The walk from the left gives the child rated 5 four candies, while the rule on the right only asks for 2. Writing 2 over the 4 would leave that child with fewer candies than the child rated 4 beside them, who has 3.
Mixing both counts in one array is safe. The walk from the right only uses a child's number when that child is rated lower than the child on their left. Such a child's climb from the left is just 1, so their number is exactly their climb from the right.
Why the total is the smallest
Could a cleverer hand-out use fewer candies? No. A climb of three children forces at least 1, 2 and 3 candies along it, because each step up needs at least one more. Every child ends up with the length of one of their two climbs, which that climb forces anyway, so no child can get less.
Java Solution
The method candy
- First, make an array
with one number per child, and fill it with 1 usingcandies , since every child gets at least one.Arrays.fill(candies, 1) - A first loop walks
from the second child to the last. Wheni is greater thanratings[i] , it setsratings[i - 1] tocandies[i] . This is the climb from the left.candies[i - 1] + 1 - A second loop walks
back from the second-to-last child to the first. Wheni is greater thanratings[i] , it setsratings[i + 1] to the larger of its current value andcandies[i] , usingcandies[i + 1] + 1 .Math.max - Finally, a third loop adds up the numbers in
intocandies , which the method returns.total
The main
import java.util.Arrays;
public class CandyDistribution {
public static int candy(int[] ratings) {
int n = ratings.length;
int[] candies = new int[n];
Arrays.fill(candies, 1); // everyone gets at least one
for (int i = 1; i < n; i++) { // climb from the left
if (ratings[i] > ratings[i - 1]) {
candies[i] = candies[i - 1] + 1;
}
}
for (int i = n - 2; i >= 0; i--) { // climb from the right
if (ratings[i] > ratings[i + 1]) {
candies[i] = Math.max(candies[i], candies[i + 1] + 1);
}
}
int total = 0;
for (int c : candies) {
total += c;
}
return total;
}
public static void main(String[] args) {
System.out.println(candy(new int[] {1, 0, 2}));
System.out.println(candy(new int[] {1, 2, 2}));
System.out.println(candy(new int[] {1, 3, 5, 4, 2, 1}));
System.out.println(candy(new int[] {1, 3, 4, 5, 2}));
System.out.println(candy(new int[] {3, 2, 1}));
System.out.println(candy(new int[] {2, 2, 2}));
System.out.println(candy(new int[] {5}));
}
}
Running it prints:
5
4
13
11
6
3
1
Look at the third line: 13 is the total from the picture, where the child rated 5 gets 4 candies from the climb on the right. Above it, 5 and 4 are the answers to Example 1 and Example 2.
The fourth line, 11, comes from 1, 3, 4, 5, 2, where the children get 1, 2, 3, 4 and 1 candies. Replace Math.maxcandies[i] = candies[i + 1] + 1
The falling line 3, 2, 1 gets 3 + 2 + 1 = 6, all from the second loop, since nothing climbs from the left. Three equal ratings print 3, one candy each, because equal neighbours set no rule. The single child on the last line gets 1.
Complexity
The work is filling the array and three walks along the line, each visiting every child once.
- Time: O(n), where n is the number of children.
and each of the three loops do a fixed amount of work per child.Arrays.fill - Space: O(n) for
, onecandies per child. Both walks update it in place, and the total is a singleint .int