算法跟学Day31【代码随想录】

文章介绍了三个使用贪心算法解决的LeetCode问题:455题‘分发饼干’,通过排序和匹配策略找到能最大化满足孩子需求的方案;376题‘摆动序列’,计算给定数组中最大的摆动序列长度;53题‘最大子序和’,寻找数组中的最大连续子数组和。
摘要由CSDN通过智能技术生成

第八章 贪心算法 part01

大纲

● 理论基础
● 455.分发饼干
● 376. 摆动序列
● 53. 最大子序和

理论基础

  • 灵活应答

leetcode 455 分发饼干

class Solution {
    public int findContentChildren(int[] g, int[] s) {
        int res = 0;
        Arrays.sort(g);
        Arrays.sort(s);
        for (int i = 0, j = 0; i < g.length && j < s.length; j++) {
            if (g[i] <= s[j]) {
                res++;
                i++;
            }
        }
        return res;
    }
}

leetcode 376 摆动序列

class Solution {
    public int wiggleMaxLength(int[] nums) {
        int up = 1, down = 1;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > nums[i - 1]) up = down + 1;
            else if (nums[i] < nums[i - 1]) down = up + 1;
        }
        return Math.max(up, down);
    }
}

leetcode 53 最大子序和

class Solution {
    public int maxSubArray(int[] nums) {
        int sum = 0, res = Integer.MIN_VALUE;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            res = res > sum ? res : sum;
            if (sum < 0) sum = 0;
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值