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?
class Solution {
public:
int candy(vector<int> &ratings) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int n = ratings.size();
if(n == 0 || n == 1) return n;
int sum = 0,candies[n];
for(int i = 0;i<n;i++) candies[i] = 1;
for(int k = 1,i = 1;i<n;i++)
{
if(ratings[i] > ratings[i-1]){;
candies[i] = max(++k,candies[i]);
}else k = 1;
}
for(int k = 1,i = n-1;i >= 1;i--)
{
if(ratings[i] < ratings[i-1]){
candies[i-1] = max(++k,candies[i-1]);
}else k = 1;
}
for(int i = 0;i<ratings.size();i++)
{
sum += candies[i];
}
return sum;
}
};
132 ms