public class Solution {
public int candy(int[] ratings) {
int[] increments = new int[ratings.length];
// From left to right
for(int i = 1, increment = 1; i < ratings.length; i++) {
if(ratings[i] > ratings[i - 1]) {
increments[i] = Math.max(increments[i], increment++);
} else {
increment = 1;
}
}
// From right to left
for(int i = ratings.length - 2, increment = 1; i >= 0; i--) {
if(ratings[i] > ratings[i + 1]) {
increments[i] = Math.max(increments[i], increment++);
} else {
increment = 1;
}
}
int sum = ratings.length;
for(int i = 0; i < ratings.length; i++) {
sum += increments[i];
}
return sum;
}
}
Time: O(n)
Space: O(n)