Leetcode 之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?

理解题目是个蛋疼的东西。
题目大意:几个小孩站一排,每个小孩有个等级值,现在给小孩发糖,发的时候要遵守2个规则:
(1)每个小孩至少一颗糖
(2)两个相邻的小孩中,等级大的小孩一定比等级小的小孩糖多,求发糖的数目的最小值。(等级相同的可以有多有少)


根据题目的意思,我们可以知道为了确保左边和右边等级有相差的,分的糖果不一样。所有我们可以把数组从左边看,然后左边比右边等级大的,可以拿到多的糖果,再然后从右边看,右边比左边等级大的,可以拿到多的糖果。

具体算法如下:

算法2:初始化所有小孩糖数目为1,从前往后扫描,如果第i个小孩等级比第i-1个高,那么i的糖数目等于i-1的糖数目+1;从后往前扫描,如果第i个的小孩的等级比i+1个小孩高,但是糖的数目却小或者相等,那么i的糖数目等于i+1的糖数目+1。

该算法时间复杂度为O(N)


具体代码实现如下所示:

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution
{
public:
     int candy(vector< int> &ratings)
    {
         int len = ratings.size();
        vector< int> candyNum(len,  1);
         for( int i =  1; i < len; i++)
        {
             if(ratings[i -  1] < ratings[i])
            {
                candyNum[i] = candyNum[i -  1] +  1;
            }
        }

         for( int i = len -  2; i >=  0; i--)
        {
             if(ratings[i] > ratings[i +  1] && candyNum[i] <= candyNum[i +  1])
            {
                candyNum[i] = candyNum[i +  1] +  1;
            }
        }

         int ret =  0;
         for( int i =  0; i < len; i++)
        {
            ret += candyNum[i];
        }

         return ret;

    }
};





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值