边工作边刷题:70天一遍leetcode: day 12-1
Candy
要点:又是左右扫描的题,从左向右简单,就是初始为1,和左边的rating比较。从右向左就直接用一个right变量,这个值每次更新都是最终i的糖果数同时作为前一个最终值的依据:初始为最后一个left的值,之后就是根据rating更新取大。
class Solution(object):
def candy(self, ratings):
"""
:type ratings: List[int]
:rtype: int
"""
n = len(ratings)
left = [1]*n
for i in range(1, n):
if ratings[i]>ratings[i-1]:
left[i]=left[i-1]+1
right = left[n-1]
minCandy = right
for i in range(n-2, -1, -1):
if ratings[i]>ratings[i+1]:
right = max(right+1, left[i])
else:
right=left[i]
minCandy +=right
return minCandy