【leetcode】135. Candy
题目如下:
解题思路:如下图,只需要找出数组中所有的拐点(前后值相等也认为是拐点)。最低点分配的糖果是1个,最高点分配的糖果是max(到左边最低点的距离,到右边最低点的距离),因为次高点与最低点之间每个点分配的糖果构成公差为1的等差数列,因此很容易就能求出相邻的最高点和最低点组成的线段中所有点分配的糖果的总和,进而求出所有糖果的总和。
代码如下:
class Solution(object): def candy(self, ratings): """ :type ratings: List[int] :rtype: int """ bottomList = [0] res = 0 dp = [1 for x in ratings] for i in xrange(1,len(ratings)-1): if ratings[i] <= ratings[i-1] and ratings[i] <= ratings[i+1]: bottomList.append(i) elif ratings[i] >= ratings[i-1] and ratings[i] >= ratings[i+1]: bottomList.append(i) bottomList.append(len(ratings)-1) for i in xrange(len(bottomList)-1): if ratings[bottomList[i]] > ratings[bottomList[i+1]]: diff = bottomList[i+1] - bottomList[i] + 1 count = diff for j in xrange(bottomList[i],bottomList[i+1]+1): dp[j] = max(count,dp[j]) count -= 1 elif ratings[bottomList[i]] < ratings[bottomList[i+1]]: #diff = ratings[bottomList[i+1]] - ratings[bottomList[i]] + 1 count = 1 for j in xrange(bottomList[i], bottomList[i+1] + 1): dp[j] = max(count, dp[j]) count += 1 else: pass #print bottomList #print dp return sum(dp)