-----QUESTION-----
There are
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?
-----SOLUTION-----
class Solution {
public:
int candy(vector<int> &ratings) {
vector<int> new_ratings(ratings.size(), 1);
for(int i = 1; i < ratings.size(); i++) //for the first time, scan from beginning
{
if(ratings[i] > ratings[i-1])
{
new_ratings[i] = new_ratings[i-1]+1;
}
}
for(int i=ratings.size()-2;i>=0;i--){ //for the second time, scan from the end
if(ratings[i]>ratings[i+1]&&new_ratings[i]<=new_ratings[i+1]){
new_ratings[i]=new_ratings[i+1]+1;
}
}
int sum=0;
for(int i=0;i<new_ratings.size();i++){
sum+=new_ratings[i];
}
return sum;
}
};