Candy
Difficulty: Hard · Pattern: Greedy · LeetCode #135
Children stand in a line with ratings. Each child gets at least one candy, and a child with a higher rating than a neighbor must get more candies than that neighbor. Return the minimum total number of candies.
Examples
text
[1,0,2] → 5 (2,1,2)
[1,2,2] → 4 (1,2,1; equal neighbors have no constraint)Hints
- Split the rule into two independent constraints: compared to the left neighbor, and compared to the right neighbor.
- Satisfy each with its own pass, then combine.
Approach
left[i]: start at 1 everywhere. Scan left to right: ifr[i] > r[i−1], thenleft[i] = left[i−1] + 1.- Scan right to left with a running
right: ifr[i] > r[i+1], thenright += 1, otherwise resetright = 1. - Child i gets
max(left[i], right). That's the smallest value satisfying both constraints.
Each pass gives the minimum needed for its own constraint, and taking the max satisfies both while staying minimal. O(n) time. An O(1)-space version counts up and down slopes.
Complexity
Time: O(n). Space: O(n).
Python solution
def candy(ratings):
n = len(ratings)
left = [1] * n
for i in range(1, n):
if ratings[i] > ratings[i - 1]:
left[i] = left[i - 1] + 1
total, right = left[-1], 1
for i in range(n - 2, -1, -1):
right = right + 1 if ratings[i] > ratings[i + 1] else 1
total += max(left[i], right)
return totalJavaScript solution
function candy(ratings) {
const n = ratings.length, c = new Array(n).fill(1);
for (let i = 1; i < n; i++) if (ratings[i] > ratings[i - 1]) c[i] = c[i - 1] + 1;
for (let i = n - 2; i >= 0; i--) if (ratings[i] > ratings[i + 1]) c[i] = Math.max(c[i], c[i + 1] + 1);
return c.reduce((a, b) => a + b, 0);
}