455.分发饼干
题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
文档讲解:代码随想录
视频讲解:贪心算法,你想先喂哪个小孩?| LeetCode:455.分发饼干_哔哩哔哩_bilibili
C++代码:
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(),g.end());
sort(s.begin(),s.end());
int index = 0;
for(int i = 0; i < s.size(); i++) {
if(index < g.size() && g[index] <= s[i]){
index++;
}
}
return index;
}
};
376. 摆动序列
题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
文档讲解:代码随想录
视频讲解:贪心算法,寻找摆动有细节!| LeetCode:376.摆动序列_哔哩哔哩_bilibili
C++代码:
class Solution {
public:
int wiggleMaxLength(vector<int>& nums) {
if (nums.size() <= 1) return nums.size();
int curDiff = 0;
int preDiff = 0;
int result = 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)) {
result++;
preDiff = curDiff;
}
}
return result;
}
};
53. 最大子序和
题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
文档讲解:代码随想录
视频讲解:贪心算法的巧妙需要慢慢体会!LeetCode:53. 最大子序和_哔哩哔哩_bilibili
C++代码:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int result = INT32_MIN;
int count = 0;
for (int i = 0; i < nums.size(); i++) {
count += nums[i];
if (count > result) {
result = count;
}
if (count <= 0) count = 0;
}
return result;
}
};