代码随想录二刷Day31
今日任务
455.分发饼干
376.摆动序列
53.最大子序和
语言:C++
455. 分发饼干
链接:https://leetcode.cn/problems/assign-cookies/
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(), g.end());
sort(s.begin(), s.end());
int res = 0;
int startIdx = 0;
for(int i = 0; i < g.size(); i++){
for(int j = startIdx; j < s.size(); j++){
if(s[j] >= g[i]){
res++;
startIdx = j + 1;
break;
}
}
}
return res;
}
};
376. 摆动序列
链接:https://leetcode.cn/problems/wiggle-subsequence/
思路有些复杂,参考卡哥的代码
class Solution {
public:
int wiggleMaxLength(vector<int>& nums) {
if(nums.size() <= 1) return nums.size();
int preDiff = 0;
int curDiff = 0;
int res = 1;
for(int i = 1; i < nums.size(); i++){
curDiff = nums[i] - nums[i - 1];
if((preDiff <= 0 && curDiff > 0) || (preDiff >= 0 && curDiff < 0)){
res++;
preDiff = curDiff;
}
}
return res;
}
};
53. 最大子序和
链接:https://leetcode.cn/problems/maximum-subarray/
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int res = INT_MIN; //不可设置为0,因为有可能数组中都是负数
int curSum = 0;
for(int i = 0; i < nums.size(); i++){
curSum += nums[i];
if(curSum > res) res = curSum;
//小于0时之前经过的位置得到的和都抛弃掉,因为哪怕后面有更大的数字,负数也只会让和变小
if(curSum < 0) curSum = 0;
}
return res;
}
};