【代码随想录Day31】贪心算法/DP

455 分发饼干

https://leetcode.cn/problems/assign-cookies/description/

方法一:排序,从小大大遍历饼干,如果饼干太小剩的人里最小胃口的人也不够吃,那么这个饼干浪费,否则喂饱一个人。方法二,排序,从大到小遍历人,如果人里面最大胃口的吃剩下的最大的饼干也不够吃,那么放弃这个人,他不可能被喂饱。

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

class Solution {  //2
    public int findContentChildren(int[] g, int[] s) {
        Arrays.sort(s);
        Arrays.sort(g);
        int count = 0;
        for (int i = g.length - 1, j = s.length - 1; i >= 0 && j >= 0; i--) {
            if (s[j] >= g[i]) {
                count++;
                j--;
            } 
        }
        return count;
    }
}

376 摆动序列

https://leetcode.cn/problems/wiggle-subsequence/ 方法一,dp,记上升和下降两个方向上以i为结束的最长序列。方法二贪心,没懂。

class Solution {  // DP
    public int wiggleMaxLength(int[] nums) {
        int[] increase = new int[nums.length];
        int[] decrease = new int[nums.length];
        Arrays.fill(increase, 1);
        Arrays.fill(decrease, 1);
        int result = 1;
        for (int i = 1; i < nums.length; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[i] > nums[j]) {
                    increase[i] = Math.max(increase[i], decrease[j] + 1);
                } else if (nums[i] < nums[j]) {
                    decrease[i] = Math.max(decrease[i], increase[j] + 1);
                } 
                result = Math.max(result, Math.max(increase[i], decrease[i]));
            }
        }
        return result;
    }
}

53 最大子数组和

https://leetcode.cn/problems/maximum-subarray/

遍历到i时,此刻prefixsum - 以前最小的prefixsum = 以i为结尾的最大子数组和

class Solution {
    public int maxSubArray(int[] nums) {
        int minPrefixSum = 0;
        int result = Integer.MIN_VALUE;
        int prefixSum = 0;
        for (int i = 0; i < nums.length; i++) {
            prefixSum += nums[i];
            result = Math.max(result, prefixSum - minPrefixSum);
            minPrefixSum = Math.min(prefixSum, minPrefixSum);
        }
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值