题目描述:
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) {
vector<int> ans(ratings.size(),1);
for (int i = 1; i < ratings.size(); i++)
{
if(ratings[i]>ratings[i-1])
ans[i]=ans[i-1]+1;
}
for (int i= ratings.size()-1; i>0 ; i--)
{
if(ratings[i-1]>ratings[i])
ans[i-1]=max(ans[i]+1,ans[i-1]);
}
int result=0;
for (int i = 0; i < ratings.size(); i++)
{
result+=ans[i];
}
return result;
}