```
public class Solution {
public int candy(int[] ratings) {
int sum = 1;
for(int i=0;i<ratings.length-1;){
int ascend = 1;
int descend = 1;
while(i<ratings.length-1&&ratings[i]<ratings[i+1]){
ascend++;
i++;
}
while(i<ratings.length-1&&ratings[i]>ratings[i+1]){
descend++;
i++;
}
if(ascend>=descend){
sum+=(ascend*(ascend+1)/2);
descend--;
sum+=(descend*(descend+1)/2);
}else{
sum+=(descend*(descend+1)/2);
ascend--;
sum+=(ascend*(ascend+1)/2);
}
sum--;
}
return sum;
}
}
```