代码随想录训练营第31天| 455.分发饼干、376. 摆动序列、53. 最大子序和

本文介绍了LeetCode中的三个编程问题,涉及贪心算法的应用:Solution类中的findContentChildren用于分发饼干的最优策略,wiggleMaxLength检测摆动序列,以及maxSubArray求解最大子数组和。这些问题展示了如何在这些场景中使用贪心方法解决问题。
摘要由CSDN通过智能技术生成

455.分发饼干

题目链接:455. 分发饼干 - 力扣(LeetCode)

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

376. 摆动序列

题目链接:376. 摆动序列 - 力扣(LeetCode)

class Solution {
    public int wiggleMaxLength(int[] nums) {
        int ans = 1;
        int j = 0, k = 0;
        for(int i = 1; i < nums.length; ++i) {
            if(nums[i] != nums[i-1]) {
                j = i;
                ++ans;
                break;
            }
        }
        if(j == 0) {
            return 1;
        }
        for(int i = j+1; i < nums.length; ++i) {
            if(nums[i] == nums[i-1]) {
                continue;
            }
            if((nums[j] - nums[k]) * (nums[i] - nums[j]) > 0) {
                j = i;
            }else {
                ++ans;
                k = j;
                j = i;
            }
        }
        return ans;
    }
}

这种类型的题,如果用贪心做,就是找波峰和波谷。

53. 最大子序和

题目链接:53. 最大子数组和 - 力扣(LeetCode)

class Solution {
    public int maxSubArray(int[] nums) {
        int max = nums[0];
        int ans = nums[0];
        for(int i = 1; i < nums.length; ++i) {
            max = nums[i] > nums[i] + max ? nums[i] : nums[i] + max;
            ans = max > ans ? max : ans;
        }
        return ans;
    }
}

有点类似前缀和的感觉

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值