原题目:https://leetcode-cn.com/problems/candy/
思路一:
使用两个数组a1,a2分别保留糖果数目。对a1从左向右遍历rating,如果rating[i] > rating[i-1],那么a1[i] = a1[i-1]+1,使用同样的方法从右向左遍历rating,a2记录糖果数目。最后孩子的糖果数是两个中的较大者。
思路二:
有了第一种方法,我们可以考虑使用一个数组进行存储,首先使用相同的方法从左向右遍历rating,a1记录糖果数。从右向左遍历时,如果满足了rating[i] > rating[i+1],那么a1[i] = max(a1[i],a1[i+1],1);
代码:
//思路一
class Solution {
public:
int candy(vector<int>& ratings) {
vector<int> a1(ratings.size(),1);
vector<int> a2(ratings.size(),1);
for(int i=1;i<ratings.size();i++){
if(ratings[i] > ratings[i-1]){
a1[i] = a1[i-1]+1;
}
}
for(int i=ratings.size()-2;i>=0;i--){
if(ratings[i] > ratings[i+1]){
a2[i] = a2[i+1]+1;
}
}
int sum = 0;
for(int i=0;i<ratings.size();i++){
sum += max(a1[i],a2[i]);
}
return sum;
}
};
//思路二
class Solution {
public:
int candy(vector<int>& ratings) {
vector<int> a1(ratings.size(),1);
for(int i=1;i<ratings.size();i++){
if(ratings[i] > ratings[i-1]){
a1[i] = a1[i-1]+1;
}
}
int sum = a1[a1.size()-1];
for(int i=ratings.size()-2;i>=0;i--){
if(ratings[i] > ratings[i+1]){
a1[i] = max(a1[i],a1[i+1]+1);
}
sum += a1[i];
}
return sum;
}
};