题目描述
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.
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?
IDEA
从前向后遍历,检查是否满足,不满足则进行调整
再从后向前遍历,检查是否满足,不满足则进行调整
CODE
class Solution {
public:
int candy(vector<int> &ratings) {
int n=ratings.size();
vector<int> candys(n,1);
for(int i=1;i<n;i++){
if(ratings[i]>ratings[i-1]&&candys[i]<=candys[i-1]){
candys[i]=candys[i-1]+1;
}
}
for(int i=n-1;i>0;i--){
if(ratings[i-1]>ratings[i]&&candys[i-1]<=candys[i]){
candys[i-1]=candys[i]+1;
}
}
int sum=0;
for(int i=0;i<n;i++){
sum+=candys[i];
}
return sum;
}
};