Scribbling

LeetCode: 135. Candy 본문

Computer Science/Coding Test

LeetCode: 135. Candy

focalpoint 2022. 2. 3. 10:35

Key idea: one's number of candies is affected by all the left and right neighbors.

So we iterate the list twice, forward and backward.

class Solution:
    def candy(self, ratings: List[int]) -> int:
        n = len(ratings)
        candies = [1] * n
        # forward pass
        for i in range(1, n):
            if ratings[i] > ratings[i-1]:
                candies[i] = candies[i-1] + 1
        # backward pass
        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)