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个孩子站成一排,每个孩子分配一个分值,给这些孩子派发糖果,
满足如下:
每个孩子至少一个,分值更高的孩子比他的相邻位的孩子获得更多的糖果
求至少分发多少个糖果?
思路:
从左到右遍历,保证该方向上分数更大的获得的糖果更多;
从右到左遍历,保证这个方向上分数更大的获得的糖果跟多;
[cpp] view plain copy
class Solution
{
public:
int candy(vector<int>& ratings)
{
int len = ratings.size();
if (len==1)
{
return 1;
}
int sum = 0;
vector<int> tmpVec(len, 1); //初始化每个孩子的糖果数设置为1
//从左扫描
for (int i=1; i<len; i++)
{
if (ratings[i]>ratings[i-1])
{
tmpVec[i] = tmpVec[i - 1] + 1;
}
}
//从右向左
for (int i=len-2; i>=0; i--)
{
if (ratings[i]>ratings[i + 1] && tmpVec[i] <= tmpVec[i + 1])
{
tmpVec[i] = tmpVec[i + 1] + 1;
}
}
for (int i=0; i<len; i++)
{
sum += tmpVec[i];
}
return sum;
}
};