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?
cpp代码如下:
class Solution {
public:
int candy(vector<int> &ratings) {
int s=ratings.size();
if(s==0)return 0;
vector<int> tmp;
tmp.resize(s);
tmp[0]=1;
for(int i=1;i<s;++i){
if(ratings[i]>ratings[i-1])tmp[i]=tmp[i-1]+1;
else tmp[i]=1;
}
int ans=tmp[s-1];
tmp[s-1]=1;
for(int i=s-2;i>=0;--i){
if(ratings[i]>ratings[i+1]){
int t=tmp[i+1]+1;
ans+=t>tmp[i]?t:tmp[i];
tmp[i]=t;
}else{
ans+=tmp[i];
tmp[i]=1;
}
}
return ans;
}
};