【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;
        
    }
};

二、写在后面

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

相关推荐
All for pursuit.3 小时前
【链表-9】146.LRU缓存
数据结构·c++·算法·leetcode
圣保罗的大教堂4 小时前
leetcode 1477. 找两个和为目标值且不重叠的子数组 中等
leetcode
hanlin035 小时前
刷题笔记:力扣第144题-二叉树的前序遍历
笔记·算法·leetcode
圣保罗的大教堂6 小时前
leetcode 3629. 通过质数传送到达终点的最少跳跃次数 中等
leetcode
圣保罗的大教堂6 小时前
leetcode 1914. 循环轮转矩阵 中等
leetcode
wabs6668 小时前
关于二叉树【力扣100.相同的树的思考】
数据结构·c++·算法·leetcode·二叉树·递归法
alphaTao8 小时前
LeetCode 每日一题 2026/9/14-2026/9/20
算法·leetcode
hanlin038 小时前
刷题笔记:力扣第560题-和为k的子数组
笔记·算法·leetcode
Navigator_Z21 小时前
LeetCode //C - 1252. Cells with Odd Values in a Matrix
c语言·算法·leetcode
语戚1 天前
力扣 1621. 大小为K的不重叠线段的数目:动态规划(Java 实现)
java·算法·leetcode·动态规划·力扣·dp