int candy(vector<int> &ratings) {
int n = ratings.size();
int* candy = new int[n];
for(int i = 0; i < n; i++) {
candy[i] = 1;
}
for(int i = 1; i < n; i++) {
if(ratings[i] > ratings[i-1] && candy[i] <= candy[i-1]) {
candy[i] = candy[i-1] + 1;
}
}
for(int i = n-2; i >= 0; i--) {
if(ratings[i] > ratings[i+1] && candy[i] <= candy[i+1]) {
candy[i] = candy[i+1] + 1;
}
}
int candies = 0;
for(int i = 0; i < n; i++) {
candies += candy[i];
}
return candies;
}
先从前往后遍历,遇到ratings比前一个人高而得到candy少的,多给他1个candy
再从后往前遍历,遇到ratings比后一个人高而得到candy少的,多给他1个candy