LeetCode135 分发糖果
贪心
分别考虑左右,对于左侧,如果 \(ratings[i] > ratings[i - 1]\),则 \(left[i] = left[i - 1] + 1\),否则 \(left[i] = 1\)
右侧考虑与左侧相同
最终对于每一个位置取 \(max\)
class Solution:
def candy(self, ratings: List[int]) -> int:
n = len(ratings)
left, right = [1] * n, [1] * n
for i in range(1, n): left[i] = left[i - 1] + 1 if ratings[i] > ratings[i - 1] else 1
for i in range(n - 2, -1, -1): right[i] = right[i + 1] + 1 if ratings[i + 1] < ratings[i] else 1
for i in range(n): left[i] = max(left[i], right[i])
return sum(left)