题目
思路
双向dp。数组分为两种情况,递增和递减。第一次从前向后遍历,处理递增的情况。第二次从后向前遍历,处理递减的情况。
代码
class Solution(object):
def candy(self, ratings):
"""
:type ratings: List[int]
:rtype: int
"""
nums = [1 for i in range(len(ratings))]
for i in range(1, len(nums)):
if ratings[i] > ratings[i - 1]:
nums[i] = nums[i - 1] + 1
for j in range(len(nums) - 1)[::-1]:
if ratings[j] > ratings[j + 1]:
nums[j] = max(nums[j], nums[j + 1] + 1)
return sum(nums)