I know it requires O(n) space. But it is a good start before checking more sophisticated solutions.

```
public int candy(int[] ratings) {
int len = ratings.length;
if (len < 2) return len;
int[] candy = new int[len];
for (int i = 1; i < len; i++) candy[i] = ratings[i] > ratings[i - 1]? candy[i - 1] + 1: 1;
for (int i = len - 2 ; i >= 0; i--)
if (ratings[i] > ratings[i + 1] && candy[i] <= candy[i + 1]) candy[i] = candy[i + 1] + 1;
int sum = 0;
for (int i: candy) sum += i;
return sum;
}
```