7.11 - hard - 30

135. Candy

greedy的问题一般就是从左到右或者从右到左,或者正向排序反向排序。

class Solution(object):
    def candy(self, ratings):
        """
        :type ratings: List[int]
        :rtype: int
        """
        # greedy的方法,
        # 从左到右递增的多拿一块
        # 从右到左的时候要比较一下当前值
        c = [1 for _ in range(len(ratings))]
        for i in range(1, len(ratings)):
            if ratings[i] > ratings[i-1]:
                c[i] = c[i-1] + 1
        for i in range(len(ratings)-1)[::-1]:
            if ratings[i] > ratings[i+1]:
                c[i] = max(c[i], c[i+1] + 1)
        return sum(c)

你可能感兴趣的:(7.11 - hard - 30)