[LeetCode] 135. Candy

夜歌乘年少發表於2024-07-09

和 238. Product of Array Except Self 計算除自己之外的乘積很像,先左側遍歷,再右側遍歷。
Hard不過如此。

class Solution:
    def candy(self, ratings: List[int]) -> int:
        # 1
        n = len(ratings)
        if n == 1:
            return 1
        # min element is not exist
        if all(x == ratings[0] for x in ratings):
            return n
        # else
        candy = [1] * n
        for i in range(1, n):
            if ratings[i] > ratings[i - 1]:
                candy[i] = candy[i - 1] + 1
        for i in range(n - 2, -1, -1):
            if ratings[i] > ratings[i + 1] and candy[i] <= candy[i + 1]:
                candy[i] = candy[i + 1] + 1
        return sum(candy)

image

相關文章