sagelearnai

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

  1. Split the rule into two independent constraints: compared to the left neighbor, and compared to the right neighbor.
  2. Satisfy each with its own pass, then combine.

Approach

  1. left[i]: start at 1 everywhere. Scan left to right: if r[i] > r[i−1], then left[i] = left[i−1] + 1.
  2. Scan right to left with a running right: if r[i] > r[i+1], then right += 1, otherwise reset right = 1.
  3. 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 total
JavaScript 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);
}