【代码随想录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;
    }
}

你可能感兴趣的:(代码随想录,leetcode,算法)