LeetCode || Candy

Candy

  Total Accepted: 12392  Total Submissions: 68386 My Submissions

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?

        特例:ratings为:1,3,3,4,3,2,1,0;那么candy数量应该为:1+2+2+5+4+3+2+1=20。分析其中的规律,rating相等的两个邻居candy数可以不等,我们只需要关注序列中连续的递减子序列的长度即可,比如本例中的 4,3,2,1,0,到达前四个人1,3,3,4显然我们分别应该给予1,2,3,4个candy,遇到第五个人3时,与前邻居4比是递减的,我们也给它1个,但是此时因为前邻居是4个,故不用加;接下来看2,我们给它1个,前邻居3也是1个,故应该给它加1个,但是前前邻居4是4个,故不用加;以此类推。。。

        由上述分析可以看出,我们需要记录递减子序列的长度descLen,以及子序列开头第一个人的candy数量descBegCan,在判断当前属于递减子序列的人的candy数时,我们并不能仅仅给当前candy总数加上这个长度,因为可能递减子序列的开头那个人(仅仅是开头这个人)本身已经有很多candy了,那么它不需要加1(就像上面判断到第五六个人3,2时,我们并不需要给第四个人4的candy数加1,因为它已经有了3个了,3>2>1 成立),而要看当前的长度descLen与descBegCan的大小关系,如果长度小于开头那个人的数量,那么仅加上长度减1 即可;如果二者相等,那么需要加上长度。

         代码如下:

class Solution {
public:
    int candy(vector<int> &ratings) {
        int res=0;
        int lastRat = -1, lastCan = 0,  can = 0;
        int descLen = 0, descBegCan=0;  //连续递减子序列的长度和递减序列头部的值
        for(int i=0; i<ratings.size(); ++i){
            if(ratings[i]>lastRat){
                can = lastCan+1;
                descLen = 0;
            }else if(ratings[i]==lastRat){  //相邻且rating相等的人candy可以不一样
                can = 1;
                descLen = 0;
            }else{
                can = 1;
                if(descLen==0)
                    descBegCan = lastCan;
                descLen++;
                
                if(can==lastCan){
                    if(descLen<descBegCan)
                        res += descLen-1;
                    else if(descLen==descBegCan){
                        res += descLen;
                        descBegCan++;
                    }
                }
            }
            res += can;
            lastRat = ratings[i];
            lastCan = can;
        }
        return res;
    }
};


本方法的空间复杂度为O(1),时间复杂度为O(n),应该属于最好的方法之一了。






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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值