题解 | #分糖果问题#

分糖果问题

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)
        if sum(arr) == n:
            return n
        degree = [[1] for _ in range(n)]
        for i in range(1,n):
            if arr[i]>arr[i-1]:
                degree[i][0] = degree[i-1][0]+1
        
        for i in range(2,n+1):
            if arr[n-i]>arr[n-i+1]:
                degree[n-i][0] = max(degree[n-i+1][0]+1,degree[n-i][0])
        print(degree)
        return sum(list(map(sum,degree)))

两遍循环,从前往后,当前数比前一个数大,则值+1

从后往前,当前数比后一个数大,则值+1

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务