算法修炼Day31|● 455.分发饼干 ● 376. 摆动序列 ● 53. 最大子序和

51 阅读1分钟
题目:455. 分发饼干 - 力扣(LeetCode)
代码实现:
class Solution {
    public int findContentChildren(int[] g, int[] s) {
        // 小饼干优先满足小胃口的孩子
        Arrays.sort(g);
        Arrays.sort(s);
        int start = 0;
        int count = 0;
        for (int i = 0; i < s.length && start < g.length; i++) {
            if (s[i] >= g[start]) {
                start++;
                count++;
            }
        }
        return count;
    }
}
题目:376. 摆动序列 - 力扣(LeetCode)
代码实现:
class Solution {
    public int wiggleMaxLength(int[] nums) {
        int count = 1;
        if (nums.length == 1) return count;
        int curDiff = 0;
        int preDiff = 0;
        for (int i = 1; i < nums.length; i++) {
            curDiff = nums[i] - nums[i - 1];
            if ((curDiff > 0 && preDiff <= 0) || (curDiff < 0 && preDiff >= 0)) {
                count++;
                preDiff = curDiff;
            }
        }
        return count;
    }
}
题目:53. 最大子数组和 - 力扣(LeetCode)
代码实现:
class Solution {
    public int maxSubArray(int[] nums) {
        if (nums.length == 1) return nums[0];
        int sum = 0;
        int maxValue = Integer.MIN_VALUE;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            maxValue = Math.max(sum, maxValue);
            if (sum <= 0){
                sum = 0;
            }
        }
        return maxValue;
    }
}