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