原题
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?
分析
N个小孩,每个小孩有一个等级,且每个小孩的等级如果比他临近的小孩高,那么他将得到更多的糖果。
求最少需要多少糖果才能满足上述要求,且每个小孩至少一个糖果。
模拟这个过程,可能会想到:
求最少需要多少糖果,先每个人分配一个,再根据等级依次加一个糖果。
但上述思路是会有问题的,那就是对于小孩
i
来说,假设他的等级既高于小孩
因此两次循环,一次从左到右,一次从右往左。
代码
class Solution {
public:
int candy( vector <int>& ratings)
{
int N= ratings.size();
vector<int>count(N,1);
for(int i=1;i<ratings.size();i++)
{
if(ratings[i]>ratings[i-1])
count[i]=count[i-1]+1;
}
for(int i=N-1;i>0;i--)
{
if(ratings[i]<ratings[i-1])
{
count[i-1]=max(count[i]+1,count[i-1]);
}
}
return accumulate(count.begin(),count.end(),0);
}
};