代码随想录算法训练营第二七天| 贪心算法理论基础 455.分发饼干 376. 摆动序列 53. 最大子序和

今日任务

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

贪心算法理论基础

贪心的本质是选择每一阶段的局部最优,从而达到全局最优

455.分发饼干

题目链接: . - 力扣(LeetCode)

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

376. 摆动序列

题目链接: . - 力扣(LeetCode)

class Solution {
    public int wiggleMaxLength(int[] nums) {
        int[] diffArray = new int[nums.length - 1];
        if (nums.length == 0 || nums.length == 1) {
            return nums.length;
        }
        for (int i = 0; i < nums.length - 1; i++) {
            diffArray[i] = nums[i + 1] - nums[i];
        }

        if (diffArray.length == 1 && diffArray[0] != 0) {return nums.length;}
        if (diffArray.length == 1 && diffArray[0] == 0) {return nums.length - 1;}

        int pre = diffArray[0];
        int count = 0;
        for (int i = 1; i < diffArray.length; i++) {
            if (pre == 0) {
                count++;
                pre = diffArray[i];
                continue;
            }
            if (pre * diffArray[i] < 0) {
                pre = diffArray[i];
            } else {
                count++;
            }
        }
        return pre == 0 ? nums.length - count - 1 : nums.length - count;
    }
}


53. 最大子序和

题目链接: . - 力扣(LeetCode)

class Solution {
    public int maxSubArray(int[] nums) {
        int sum = 0;
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            max = Math.max(max,sum);
            if (sum <= 0) {
                sum = 0;
            }
        }
        return max;
    }
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值