Candy
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:
- Time: O(n)
- Space: O(n)
public int candy(int[] rates)
int[] candy = new int[rates.length];
Arrays.fill(candy, 1);
for (int i = 1; i < rates.length; i++) {
if (rates[i - 1] < rates[i]) {
candy[i] = candy[i - 1] + 1;
}
}
for (int i = rates.length - 2; i >= 0; i--) {
if (rates[i] > rates[i + 1] && candy[i] <= candy[i + 1]) {
candy[i] = candy[i + 1] + 1;
}
}
int ret = 0;
for (int i = 0; i < candy.length; i++) {
ret += candy[i];
}
return ret;
}