您的位置:首页 > 其它

leetcode 135: Candy

2015-08-18 22:34 681 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: