LeetCode135:Candy

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?

Example 1:

Input: [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.

Example 2:

Input: [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
             The third child gets 1 candy because it satisfies the above two conditions.

LeetCode:链接

初始化所有孩子糖果为1颗,接下来从左到右扫描进行“修正”

假设我们只考虑左边孩子的情况,如果当前孩子大于左边孩子,那么糖果要在左边孩子基础上+1.

这样扫描一遍以后,我们可以保证,对于任意的 i > 0 有 ans[i]>ans[i-1] ( if ratings[i] >rating[i-1])

接下来从右向左扫描,如果当前孩子大于右边的孩子,并且糖果数少于右边的,要在右边的孩子基础上+1

总结如下:第一次扫描保证了每个比左边高分的孩子比左边的糖果多,第二次则是右边

class Solution(object):
    def candy(self, ratings):
        """
        :type ratings: List[int]
        :rtype: int
        """
        if len(ratings) <= 1:
            return len(ratings)
        n = len(ratings)
        ans = [1] * n
        for i in range(1, n):
            if ratings[i] > ratings[i-1]:
                ans[i] = ans[i-1] + 1

        for i in range(n-2, -1, -1):
            if ratings[i] > ratings[i+1] and ans[i] <= ans[i+1]:
                ans[i] = ans[i+1] + 1

        return sum(ans)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值