leetcode 135: Candy

Two method can be used here.

The first one is using greedy algorithm twice from begin to end and from end to begin. if the current rating is bigger than the previous one, the number will be added into the sum will increase by 1. Using this method will require you to create an array to save the result of the first scan.

The second method is just scan the ratings for one time. If ratings[i]>ratings[i-1], add the number to be added. If ratings[i]==ratings[i-1], make the number be 1. And if ratings[i]<ratings[i-1], add another loop to find the end of the descending sequence, and then give that child 1 candy, so the whole candy given to the sequence can be determined.

class Solution {
public:
    int candy(vector<int>& ratings) {
        if(ratings.size()<=1)
            return ratings.size();
        int sum=1,num=1,pre=1;//pre is to save the candy for the start of a descending sequence
        for(int i=1;i<ratings.size();i++)
        {
            if(ratings[i]<ratings[i-1])
            {
                int j=i;
                while(j<ratings.size()&&ratings[j]<ratings[j-1])
                    j++;//after the loop, j will be one position after the end
                int len=j-i;//i is the second in the sequence
                if(pre<len+1)//len+1 is the minimum candy child i-1 should have
                    sum+=len+1-pre;
                sum+=(1+len)*len/2;
                i=j-1;
                num=1;
            }
            else
            {
                if(ratings[i]>ratings[i-1])
                    num++;
                else
                    num=1;
                sum+=num;
                pre=num;
            }
        }
        return sum;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值