```
public class Solution {
public int candy(int[] ratings) {
int len = ratings.length;
int res = len;
int start = 0;
int height = 0;
for (int i = 0; i < len - 1; ) {
while (i < len - 1 && ratings[i] == ratings[i + 1]) i++;
start = i;
while (i < len - 1 && ratings[i] < ratings[i + 1]) {
res += (i - start + 1);
i++;
}
height = i - start;
start = i;
while (i < len - 1 && ratings[i] > ratings[i + 1]) {
res += (i - start + 1);
i++;
}
height = Math.min(height, i - start);
res -= height;
}
return res;
}
}
```