455. 分发饼干
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; // startIdx不能++,应该要赋值j+1!!
break;
}
}
}
return res;
}
};
376. 摆动序列
class Solution {
public:
int wiggleMaxLength(vector<int>& nums) {
int preDiff = 0;
int curDiff = 0;
int res = 1; // 默认结尾元素必是满足条件
for (int i = 0; i < nums.size() - 1; i++) {
curDiff = nums[i+1] - nums[i];
if ((preDiff >= 0 && curDiff < 0) || (preDiff <= 0 && curDiff > 0)) {
res++;
preDiff = curDiff;
}
}
return res;
}
};
53. 最大子序和
class Solution {
public:
// 贪心策略;每次加完nums[i],若变成负数,则跳转
int maxSubArray(vector<int>& nums) {
int sum = 0;
int maxSum = INT_MIN;
for (int i = 0; i < nums.size(); i++) {
sum += nums[i];
maxSum = max(maxSum, sum);
if (sum < 0) {
sum = 0;
}
}
return maxSum;
}
};