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?
Java:
public class Solution {
public int candy(int[] ratings) {
int[] left = new int[ratings.length];
int[] right = new int[ratings.length];
int k = 1;
left[0] = 1;
for(int i=1; i<ratings.length; i++)
{
if(ratings[i] > ratings[i-1])
left[i] = ++k;
else
{
k = 1;
left[i] =k;
}
}
k = 1;
right[ratings.length - 1] = k;
int sum=Math.max(left[ratings.length - 1],right[ratings.length - 1]);
for(int j = ratings.length -2; j>=0;j--)
{
if(ratings[j] > ratings[j+1]) right[j] = ++k;
else
{
k=1;
right[j] = k;
}
sum = Math.max(left[j],right[j]) + sum;
}
return sum;
}
}