和 238. Product of Array Except Self 计算除自己之外的乘积很像,先左侧遍历,再右侧遍历。
Hard不过如此。
class Solution:def candy(self, ratings: List[int]) -> int:# 1n = len(ratings)if n == 1:return 1# min element is not existif all(x == ratings[0] for x in ratings):return n# elsecandy = [1] * nfor i in range(1, n):if ratings[i] > ratings[i - 1]:candy[i] = candy[i - 1] + 1for i in range(n - 2, -1, -1):if ratings[i] > ratings[i + 1] and candy[i] <= candy[i + 1]:candy[i] = candy[i + 1] + 1return sum(candy)