题解 | #分糖果#
分糖果
http://www.nowcoder.com/practice/74a62e876ec341de8ab5c8662e866aef
# # 动态规划从左往右循环一次,保证比左边邻居大,从右往左保证比右边邻居大 # @param ratings int整型一维数组 # @return int整型 # class Solution: def candy(self , ratings ): # write code here if not ratings : return 0 dp =[1] *len(ratings) for i in range(1, len(ratings)): if ratings[i] > ratings[i-1]: dp[i] = dp[i-1] +1 for j in range(len(ratings)-2,-1,-1): if ratings[j] >ratings[j+1] and dp[j] <=dp[j+1]: dp[j] = dp[j+1] +1 return sum(dp)