【算法/贪心算法/简单题】题解+详细备注(共3题)
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(),g.end());
sort(s.begin(),s.end());
int result{};
int nG = g.size()-1;
int nS = s.size()-1;
while(nG >=0 && nS >= 0){
if(s[nS] >= g[nG]){
nG--;
nS--;
result++;
}else{
nG--;
}
}
return result;
}
};
class Solution {
public:
int largestSumAfterKNegations(vector<int>& nums, int k) {
sort(nums.begin(),nums.end(),[&](auto&&a,auto&&b){
return abs(a) < abs(b);
});
for(int i = nums.size()-1;i>=0;--i){
if(k == 0) break;
if(nums[i] < 0){
nums[i] = -nums[i];
k--;
}
}
while(k > 0){
nums[0]*=-1;
k--;
}
return accumulate(nums.begin(),nums.end(),0);
}
};
class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
int fiveCount{};
int tenCount{};
for(int i{};i<bills.size();++i){
if(bills[i] == 5){
fiveCount++;
}else if(bills[i] == 10){
if(fiveCount == 0) return false;
tenCount++;
fiveCount--;
}else{
if(fiveCount >= 1 && tenCount >= 1){
fiveCount--;
tenCount--;
continue;
}
if(tenCount == 0 && fiveCount >= 3){
fiveCount-=3;
continue;
}
return false;
}
}
return true;
}
};