Hand out the fewest candies so higher-rated kids beat their neighbours. Sweep left to right, then right to left, keeping the larger count.
▼The problem
LeetCode 135 (Hard). n children stand in a line, each with a rating. Give out candies so that every child gets at least one, and a child with a higher rating than a neighbour gets more candies than that neighbour. Return the minimum number of candies.
Examples (LeetCode's): [1,0,2] → 5 (2, 1, 2) and [1,2,2] → 4 (1, 2, 1: equal ratings ask for nothing).
The solution
def candy(ratings):
n = len(ratings)
candies = [1] * n
for i in range(1, n):
if ratings[i] > ratings[i - 1]:
candies[i] = candies[i - 1] + 1
for i in range(n - 2, -1, -1):
if ratings[i] > ratings[i + 1]:
candies[i] = max(candies[i], candies[i + 1] + 1)
return sum(candies)Transcript
Candy. Children stand in a line, each with a rating. Hand out candy by two rules: every child gets at least one, and a child rated higher than a neighbor gets more than that neighbor. What's the fewest candies in total?
Take ratings one, zero, two. The middle child rates lowest, so she gets one. Both neighbors outrank her, so each needs two: five in all. Now one, two, two: one, then two, and the last child ties her neighbor. A tie asks for nothing, so she gets one. Four.
The slow way: give everyone one, then sweep the line, bumping any child who breaks a rule, until a sweep changes nothing. On a falling line, five down to one, each sweep settles just one more child. That's up to n sweeps of n children: order n squared.
The trick: split the rule into a left half and a right half, with two greedy passes. Left to right, a child who outranks her left neighbor gets one more than her. Then right to left, a child who outranks her right neighbor needs one more than that, and keeps the larger count.
In code, start everyone at one. The left pass walks forward: if a rating beats the one before it, take the previous count plus one. The right pass walks back: if a rating beats the one after it, take the max of its count and the next count plus one. Return the sum.
Now one, three, five, four, two, one. Left pass: one, two, three as the ratings climb. Four is lower than five, so it drops back to one, and so do the last two. Right pass, from the end: two beats one, so two. Four beats two: three. Five beats four: the left pass gave it three, but the right needs four, so four wins. Total: thirteen.
Two passes over n children: order n time. The candies list takes order n space; a slope-counting version gets that down to order one.
Climb from the left, climb from the right, keep the larger. That's Candy.