【算法/贪心算法/两个维度权衡问题】题解+详细备注(共2题)
class Solution {
public:
int candy(vector<int>& ratings) {
int n = ratings.size();
vector<int> result(n,1);
for(int i{1};i < n;++i){
if(ratings[i] > ratings[i-1]){
result[i] = max(result[i],result[i-1]+1);
}
}
for(int i{n-2};i>=0;i--){
if(ratings[i] > ratings[i+1]){
result[i] = max(result[i],result[i+1] + 1);
}
}
return accumulate(result.begin(),result.end(),0);
}
};
class Solution {
public:
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
sort(people.begin(),people.end(),[](auto&&a,auto&&b){
if(a[0] == b[0]) return a[1] < b[1];
return a[0] > b[0];
});
vector<vector<int>> que;
for(int i{};i<people.size();++i){
int position = people[i][1];
que.insert(que.begin() + position,people[i]);
}
return que;
}
};
|