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?
刚开始以为只有等级高的就比等级低的糖多,忽略此处,只针对相邻的的小孩。
此题思路:
先从左向右扫描,只要右边的大于左边的权值,且糖右边小于等于左边,右边值才需更新
再从右向左扫描,只要左边的大于右边的权值,且糖左边小于等于右边,左边值才需更新
int candy(vector<int> &ratings) {
/* 注释的代码是在不考虑相邻的情况
int result = 1;
int increment = 0;
int next_value =1;
//第一种方法先排序。理解错误
sort(ratings.begin(),ratings.end());
for(int i = 1;i<ratings.size();i++)
{
if(ratings.at(i-1)<ratings.at(i))
{
increment += 1;
next_value += increment;
}
result += next_value;
}
return result;
}
*/
int result = 0 ;//刚开始未初始化一直通不过。报错
int size = ratings.size();
vector<int> candy(size,1);
//观察从左到右的影响,右大的情况
for(int i = 1;i < size;i++)
{
if(ratings[i-1] < ratings[i] && candy[i-1] >= candy[i] )
{
candy[i] = candy[i-1] + 1;
}
}
//观察从右到左的影响,左大情况
for(int j = size-1;j >= 1;j--)
{
if(ratings[j-1] > ratings[j] && candy[j-1] <= candy[j] )
{
candy[j-1] = candy[j]+1;
}
}
for(int k = 0;k <size;k++)
{
result += candy[k];
}
return result;
}