题目描述:

中文:

老师想给孩子们分发糖果,有 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.
Children with a higher rating get more candies than their neighbors.

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

 

 

题目来源:力扣

相关文章:

  • 2021-12-16
  • 2021-05-29
  • 2021-09-21
  • 2022-12-23
  • 2022-12-23
  • 2021-06-02
  • 2022-01-03
  • 2022-12-23
猜你喜欢
  • 2021-12-07
  • 2022-12-23
  • 2022-02-09
  • 2021-09-24
  • 2021-06-01
  • 2021-11-11
  • 2022-12-23
相关资源
相似解决方案