135. 分发糖果

https://leetcode-cn.com/problems/candy/

解法一:

不用考虑太复杂,两次遍历:

class Solution:
    def candy(self, ratings: 'List[int]') -> 'int':
        n = len(ratings)
        result = [1] * n  #存储糖果,初始各分配一个
        if n == 0:
            return 0
        #正向处理上坡
        for i in range(1, n):
            if ratings[i] > ratings[i-1]:
                result[i] = result[i-1]+1

        #反向处理下坡
        for j in range(n-2, -1, -1):
            if ratings[j] > ratings[j+1] and result[j] <= result[j+1]:
                result[j] = result[j+1]+1

        return sum(result)
                

最后更新于