【Day23 LeetCode】贪心算法题

一、贪心算法

贪心没有套路,只有碰运气(bushi),举反例看看是否可行,(运气好)刚好贪心策略的局部最优就是全局最优。

1、分发饼干 455

思路:按照孩子的胃口从小到大的顺序依次满足每个孩子,对于每个孩子,应该选择可以满足这个孩子的胃口且尺寸最小的饼干

CPP 复制代码
class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        sort(g.begin(), g.end());
        sort(s.begin(), s.end());
        int d1 = 0, d2 = 0;
        int cnt = 0;
        while(d2 < s.size() && d1 < g.size()){
            if(g[d1] <= s[d2++]){
                ++cnt;
                ++d1;
            }
        }
        return cnt;
    }
};

2、摆动序列 376

贪心:删除单调坡度上的节点,这个坡度就可以有两个局部峰值。所以求长度的问题变成求峰值个数。

CPP 复制代码
class Solution {
public:
    int wiggleMaxLength(vector<int>& nums) {
        int cur = 0, pre = 0;
        int ans = 1;
        for(int i=0; i<nums.size()-1; ++i){
            cur = nums[i+1] - nums[i]; // 当前的差值
            // 差值正负出现变化-->峰值出现
            if((cur > 0 && pre <= 0) || (cur < 0 && pre >= 0)){
                ++ans;
                pre = cur; // 只在摆动的时候更新
            }
        }
        return ans;
    }
};

3、最大子序和 53

思路:负的子序和只会拉低最大子序和

CPP 复制代码
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int ans = INT_MIN, s = 0;
        for(int i=0; i<nums.size(); ++i){
            s += nums[i];
            if(s > ans)
                ans = s;
            if(s < 0)
                s = 0;
        }
        return ans;
        
    }
};

二、写在后面

贪心得多练。今天的摆动序列一开始没想出来。

相关推荐
Aspect of twilight1 小时前
LeetCode华为大模型岗刷题
python·leetcode·华为·力扣·算法题
2301_807997381 小时前
代码随想录-day47
数据结构·c++·算法·leetcode
Elias不吃糖2 小时前
LeetCode每日一练(3)
c++·算法·leetcode
小年糕是糕手6 小时前
【C++】类和对象(二) -- 构造函数、析构函数
java·c语言·开发语言·数据结构·c++·算法·leetcode
sheeta199811 小时前
LeetCode 每日一题笔记 日期:2025.11.24 题目:1018. 可被5整除的二进制前缀
笔记·算法·leetcode
橘颂TA19 小时前
【剑斩OFFER】算法的暴力美学——两整数之和
算法·leetcode·职场和发展
Dream it possible!19 小时前
LeetCode 面试经典 150_二叉搜索树_二叉搜索树的最小绝对差(85_530_C++_简单)
c++·leetcode·面试
xxxxxxllllllshi19 小时前
【LeetCode Hot100----14-贪心算法(01-05),包含多种方法,详细思路与代码,让你一篇文章看懂所有!】
java·数据结构·算法·leetcode·贪心算法
-森屿安年-1 天前
LeetCode 283. 移动零
开发语言·c++·算法·leetcode
元亓亓亓1 天前
LeetCode热题100--79. 单词搜索
算法·leetcode·职场和发展