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?


思想:

总共只需要一次遍历数组,当数组元素从小到大时,最小的给1个糖果,后面依次增加1;当元素从大到小时,后面的依次减1,假如用N记录当前递减的元素的个数,这时会   遇到两种情况:

        1、不够减,则之前递减的每个孩子都多给1个糖果,则之前给予的糖果总数sum+N;

        2、到达递减与递增的拐点处时,给予孩子的糖果树为M,M大于1,则之前给予的糖果总数sum-N(M-1);

总之,思想为多退少补,让总糖果数达到最少。





针对相邻元素大小相同的情况要特殊处理,代码有点乱,总体思想就如上面所述。C++代码如下:

class Solution {
public:
    int candy(vector<int> &ratings) {
        if(ratings.size()==0)
        {
            return 0;
        }
        else
        {
            int sum=1;
            int now=1;
            int red=1;
            for(int i=1;i<ratings.size();i++)
            {
                if(ratings[i-1]<ratings[i])
                {
                    if(red!=1)
                    {
                        sum-=((now-1)*(red-1));
                        now=1;
                        red=1;
                    }      
                    sum+=(++now);
                }
                else if(ratings[i-1]>ratings[i])
                {
                    if(ratings[i-1]==ratings[i])
                    {
                        now=1;
                        sum+=now;
                    }
                    else
                    {
                        if(now==1)
                        {
                            sum+=(red+now);
                            red++;
                        }
                        else
                        {
                            sum+=(--now);
                            red++;
                        }
                    }
                }
                else if(ratings[i-1]==ratings[i])
                {
                    if(red!=1)
                    {
                        sum-=((now-1)*(red-1));
                        now=1;
                        red=1;
                        sum++;
                    }
                    else
                    {
                        now=1;
                        sum+=now;
                    }
                }
            }
            if(red!=1&&now!=1)
            {
                sum-=((now-1)*(red-1));
            }
            return sum;   
        }
    }
};


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值