题目:
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;
}
}
};