day27 贪心1
贪心解题步骤:
1.将问题分解为若干子问题
2.找出适合的贪心策略
3.求解每个子问题的最优解
4.将局部最优解堆叠成全局最优解
455.分发饼干
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
int res = 0;
sort(g.begin(), g.end());
sort(s.begin(), s.end());
for (int i = 0, j = 0; i < g.size() && j < s.size(); j ++) {
if (s[j] >= g[i]) {
res ++;
i ++;
}
}
return res;
}
};
376. 摆动序列
贪心法:
class Solution {
public:
int wiggleMaxLength(vector<int>& nums) {
if (nums.size() <= 1) {
return nums.size();
}
int curDiff = 0;
int preDiff = 0;
int res = 1;
//以i结束
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:
int maxSubArray(vector<int>& nums) {
vector<int> dp(nums.size() + 1, 0);
int res = nums[0];
for (int i = 0; i < nums.size(); i ++) {
if (dp[i] > 0) {
dp[i+1] = dp[i] + nums[i];
}
else {
dp[i+1] = nums[i];
}
res = max(res, dp[i+1]);
}
return res;
}
};