题解 | #分糖果问题#
分糖果问题
https://www.nowcoder.com/practice/76039109dd0b47e994c08d8319faa352
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# pick candy
# @param arr int整型一维数组 the array
# @return int整型
#
class Solution:
def candy(self , arr: List[int]) -> int:
# write code here
n = len(arr)
res = [1] * n
# 从左往右找,右边比左边大,递增加1,如果右边小于等于左边,默认是1
for i in range(1,n):
if arr[i]> arr[i-1]:
res[i] = res[i-1] + 1
# 从右往左找,主要处理上次默认为1的部分,如果左边比右边大但是糖果数小于右边,把左边的糖果数从1改到右边糖果数 +1
for j in range(n-2, -1, -1):
if arr[j] > arr[j+1] and res[j] <= res[j+1]:
res[j] = res[j+1] + 1
return sum(res)

