[LeetCode] Candy

题目描述:

There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give? 

从左到右遍历,将会遇到上升和下降,上升逐次加1就行,但下降就不好办了,得考虑第二个极值是不是会影响前面的极值。
化一遍遍历为两遍递增遍历就好办多了,从左到右递增一遍,再从右到左递增一遍;第二遍递增时,若遇到有数据的一定是第一遍的极值,极值点取两遍极值的最大值就行。

class Solution:
    # @param ratings, a list of integer
    # @return an integer
    def candy(self, ratings):
        n = len(ratings)
        result = [1]*n
        resultnum = 0
        for i in range(n-1,0,-1):
            if ratings[i-1]>ratings[i]:
                result[i-1] = result[i]+1
        for j in range(n-1):
            if ratings[j+1]>ratings[j]:
                temp = result[j]+1
                if result[j+1]<temp:
                    result[j+1] = temp
        for k in range(n):
            resultnum += result[k]
        return resultnum

你可能感兴趣的:(LeetCode)