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. You hand out candies under two rules. Every child gets at least one candy. A child with a higher rating than a neighbour, the child just before or just after in the line, gets more candies than that neighbour. Return the smallest total number of candies that meets both rules.

Example 1
Input: ratings = [1, 0, 2]
Output: 5
Explanation: the children get 2, 1 and 2 candies.
Example 2
Input: ratings = [1, 2, 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.
Solution

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.

Ratings 1, 3, 5, 4, 2, 1 as bars. The climb from the left gives 1, 2, 3, 1, 1, 1 and the climb from the right gives 1, 1, 4, 3, 2, 1. Each child gets the larger number, 1, 2, 4, 3, 2, 1, a total of 13.

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, all starting at 1, and walk from left to right. A child rated higher than the left neighbour gets the neighbour's number plus one; any other child keeps 1. The neighbour's number is already final when the walk reaches a child, so nothing needs a second look.

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, keeping the larger of the number already there and the new count.

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 works in these steps:

  1. First, make an array candies with one number per child, and fill it with 1 using Arrays.fill(candies, 1), since every child gets at least one.
  2. A first loop walks i from the second child to the last. When ratings[i] is greater than ratings[i - 1], it sets candies[i] to candies[i - 1] + 1. This is the climb from the left.
  3. A second loop walks i back from the second-to-last child to the first. When ratings[i] is greater than ratings[i + 1], it sets candies[i] to the larger of its current value and candies[i + 1] + 1, using Math.max.
  4. Finally, a third loop adds up the numbers in candies into total, which the method returns.

The main method runs both examples, the line from the picture, the line 1, 3, 4, 5, 2, a falling line, three equal ratings and a single child.

Java
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:

Output
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.max with the plain assignment candies[i] = candies[i + 1] + 1, and the child rated 5 drops to 2 candies. That line then prints 9, but the child rated 4 has 3 candies, more than the child rated 5.

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. Arrays.fill and each of the three loops do a fixed amount of work per child.
  • Space: O(n) for candies, one int per child. Both walks update it in place, and the total is a single int.

Product of Array Except Self also builds its answer from one walk from the left and one from the right.