力扣——candy (分糖果) python实现
题目描述: 中文: 老师想给孩子们分发糖果,有 N 个孩子站成了一条直线,老师会根据每个孩子的表现,预先给他们评分。 你需要按照以下要求,帮助老师给这些孩子分发糖果: 每个孩子至少分配到 1 个糖果。 那么这样下来,老师至少需要准备多少颗糖果呢? 英文: There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. What is the minimum candies you must give? class Solution(object): def candy(self,ratings): """ :type ratings: List[int] :rtype: int """ s = 0 n=len(ratings) s+=n tmp =[0]*n for i in range(1,n): if ratings[i]>ratings[i-1]: tmp[i] = tmp[i-1]+1 for i in range(n-2,-1,-1): if ratings[i]>ratings[i+1]: tmp[i]=max(tmp[i],tmp[i+1]+1) s+=sum(tmp) return s ? ? 题目来源:力扣 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |