135. 分发糖果
方法
左规则和右规则都要满足
class Solution {
public:
int candy(vector<int>& ratings) {
int length = ratings.size();
vector<int> left(length,1),right(length,1);
for(int i = 1; i < length; i++){
if(ratings[i-1] < ratings[i]){
left[i] = left[i-1]+1;
}
}
int sum = left[length-1];
for(int i = length-2;i>=0;i--){
if(ratings[i] > ratings[i+1]){
right[i] = right[i+1]+1;
}
sum += max(left[i],right[i]);
}
return sum;
}
};
class Solution {
public:
int candy(vector<int>& ratings) {
int length = ratings.size();
vector<int> left(length,1);
for(int i = 1; i < length; i++){
if(ratings[i-1] < ratings[i]){
left[i] = left[i-1]+1;
}
}
int sum = left[length-1];
int rear = 1;
for(int i = length-2;i>=0;i--){
if(ratings[i] > ratings[i+1]){
rear++;
}
else{
rear = 1;
}
sum += max(left[i],rear);
}
return sum;
}
};