135. 分发糖果
题目链接 | 135. 分发糖果 |
---|---|
思路 | 动态规划 |
题解链接 | 动态规划,计算最长递减序列 |
关键点 | 识别出:发放的糖果的数量实质上需要找到“最长递增子串”的长度 |
时间复杂度 | \(O(n)\) |
空间复杂度 | \(O(n)\) |
代码实现:
class Solution:
def candy(self, ratings: List[int]) -> int:
n = len(ratings)
dp_left = [1] * n
dp_right = [1] * n
for i in range(1, n):
if ratings[i] > ratings[i-1]:
dp_left[i] = dp_left[i-1] + 1
else:
dp_left[i] = 1
if ratings[n-1-i] > ratings[n-i]:
dp_right[n-1-i] = dp_right[n-i] + 1
else:
dp_right[n-1-i] = 1
answer = sum(max(left, right) for left, right in zip(dp_left, dp_right))
return answer