Leetcode#135 Candy

时间:2022-03-24 08:00:48

原题地址

遍历所有小孩的分数

1. 若小孩的分数递增,分给小孩的糖果依次+1
2. 若小孩的分数递减,分给小孩的糖果依次-1
3. 若小孩的分数相等,分给小孩的糖果设为1

当递减序列结束时,如果少分了糖果,就补上,如果多分了糖果,就减掉

究竟补多少或减多少,这很容易计算,不啰嗦了。

时间复杂度:O(n)

代码:

 int candy(vector<int> &ratings) {
int n = ratings.size();
int sum = ;
int len = ;
int prev = ; for (int i = ; i < n; i++) {
if (ratings[i] == ratings[i - ]) {
prev = ;
len = ;
sum += prev;
}
else if (ratings[i] > ratings[i - ]) {
prev++;
len = ;
sum += prev;
}
else if (ratings[i] < ratings[i - ]) {
prev--;
len++;
sum += prev;
if (i == n - || ratings[i] <= ratings[i + ]) {
sum += prev < ? ( - prev) * (len + ) : ( - prev) * len;
prev = ;
}
}
} return sum;
}