leetcode 135: Candy

来源:互联网 发布:彩虹秒赞源码 编辑:程序博客网 时间:2024/05/29 17:20

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;    }};


0 0
原创粉丝点击