I see people use an extra array to store the candy give out to each kid, and use one or two more passes to adjust the number of candies and sum them up. I'm more concerned with any O(1) space solution.

Here's my code, and I think the comment is self-explanatory. I have problem handling the case when two neighbors have the same rating. Any sparks? Thanks!

```
public int candy(int[] ratings) {
if(ratings.length == 1) return 1;
//total number of candy
int total = 0;
//current number of candies we give. suppose first kid get 1 candy. we will adjust it after the loop.
int cur = 1;
//previous kid's rating
int prevRating = ratings[0];
//minmum candy we give out to one kid
int mincandy = 1;
for(int i = 0;i < ratings.length; i++){
//I have problem here. I do not know how to handle the case where previous kid has the same rating as current one
if(prevRating == ratings[i]){
//cur = 1;? Is there a way to adjust variable cur and mincandy to get the result we want?
total += cur;
}
//if previous kid has larger rating, we decrease the current number of candy by 1
else if(prevRating > ratings[i]){
cur--;
//set minmum candy we give to a kid if necessary
if(mincandy > cur) mincandy = cur;
total += cur;
}
//if previous kid has smaller rating, we increase the current number of candy by 1
else if(prevRating < ratings[i]){
cur++;
total += cur;
}
prevRating = ratings[i];
}
//after the loop, we can adjust the total number of candies according to the minmum candy we give out to a single kid.
//for example, [4, 3, 2, 1], mincandy will be -2 here. total is -2. after the statement below, total will be 10.
total += (1-mincandy)*ratings.length;
return total;
}
```