SDE & MLE Prep

135. Candy

Problem

Children stand in a line with ratings. Give each child at least one candy, and a child with a higher rating than a neighbour must get more candies than that neighbour. Return the minimum total candies.

Example: [1,0,2] → 5 (2, 1, 2); [1,2,2] → 4 (1, 2, 1)

Constraints: n ≤ 2·10⁴.

Left→right pass satisfies "higher than left neighbour"; right→left pass satisfies "higher than right neighbour" while keeping the max.

ratings  1 0 2
L->R     1 1 2
R->L     2 1 2     total 5

Complexity: O(n).

class Solution:
    def candy(self, ratings: List[int]) -> int:
        n = len(ratings)
        c = [1] * n
        for i in range(1, n):
            if ratings[i] > ratings[i - 1]:
                c[i] = c[i - 1] + 1
        for i in range(n - 2, -1, -1):
            if ratings[i] > ratings[i + 1]:
                c[i] = max(c[i], c[i + 1] + 1)
        return sum(c)