【原创】leetCodeOj --- Candy 解题报告

题目地址:

https://leetcode.com/problems/candy/

 

题目内容:

Candy

Total Accepted: 43150 Total Submissions: 203841 Difficulty: Hard

 

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?

 

题目解析:

 

简单来讲,一个数组里的每个小孩都有权值,每个小孩都必须有一颗糖,而如果身边的小孩权值比自己低,那么自己就能多拿糖。

问最少能给几颗糖

 

容易看出,n个小孩,那么至少n颗糖,我们可以在这个基础上分配糖。

 

贪心算法:

从权值最小的小孩开始分起,每分到一个小孩时,看他是否比身边小孩的权值大,如果大,则比身边小孩最多糖数再多1;如果小,则不变。

 

为什么这个算法是对的?

 

0、由于权值比自己小的小孩已经处理过了,所以,后面不会出现权值比自己小的小孩获得的糖果数更新的情况,因此,自己的糖果数也不用更新。

 

1、由于每处理一个小孩,该小孩就不用再修改,所以从1块糖处理起时,每个小孩拿到的都是自己可以拿到的最小值。

 

具体代码:

class Solution(object):
    def candy(self, ratings):
        """
        :type ratings: List[int]
        :rtype: int
        """
        self.ratings = ratings
        if len(ratings) == 0:
            return 0
        heap = list()
        candies = list()
        for i in range(len(ratings)):
            heap.append({'index':i,'value':ratings[i]})
            candies.append(1)
        heap = sorted(heap, key=lambda x:x['value'])
        for i in range(len(heap)):
            self.get_candy(heap[i], candies)
        return sum(candies)
        
    def get_candy(self, item, candies):
        index = item['index']
        value = item['value']
        if index - 1 >= 0:
            if self.ratings[index - 1] < value:
                candies[index] = candies[index - 1] + 1
        if index + 1 < len(candies):
            if self.ratings[index + 1] < value:
                if candies[index] < candies[index + 1] + 1:
                    candies[index] = candies[index + 1] + 1

 

 

转载于:https://www.cnblogs.com/shadowmydx/p/4914215.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值