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?
Difficulty: Hard
Solution: Greedy, first from left to right, then right to left
public class Solution {
public int candy(int[] ratings) {
int len = ratings.length;
if(len == 0) return 0;
int[] nums = new int[len];
for(int i = 0; i < len; i++){
if(i > 0 && ratings[i] > ratings[i - 1]){
nums[i] = nums[i - 1] + 1;
}
else{
nums[i] = 1;
}
}
for(int i = len - 1; i>= 0; i--){
if(i < len - 1 && ratings[i] > ratings[i + 1]){
nums[i] = Math.max(nums[i + 1] + 1, nums[i]);
}
// else{
// nums[i] = 1;
// }
}
int sum = 0;
for(int i = 0; i < len; i++){
sum += nums[i];
}
return sum;
}
}