算法Day23 | Leetcode455.分发饼干、376. 摆动序列、53. 最大子序和

455.分发饼干

力扣链接

思路

贪心

代码

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

376. 摆动序列

力扣链接

思路

贪心,如果是有下平下[1,2,2,0],所以要包含等于0的情况;如果是下平平上[1,2,2,3]就不能每次都更新pre,只有遇到波峰波谷的时候再去更新,一开始len=1是当含有两个元素的时候,外面定义了pre=0但是应该算有两个连续子序列。

代码

class Solution {
    public int wiggleMaxLength(int[] nums) {
        if(nums.length<=1) return nums.length;
        int len=1;
        int pre=0;
        int cur=0;
        for(int i=1;i<nums.length;i++){
            cur=nums[i]-nums[i-1];
            if((pre>=0 && cur<0) || (pre<=0 && cur>0)){
                len++;
                pre=cur;
            }
        }
        return len;
    }
}

53. 最大子序和

力扣链接

思路

贪心,如果当前cur已经小于0了,那对后面的元素都算是削弱,所以重新置为0

代码

class Solution {
    public int maxSubArray(int[] nums) {
        if(nums.length==1) return nums[0];
        int count=Integer.MIN_VALUE;
        int cur=0;
        for(int i=0;i<nums.length;i++){
            cur+=nums[i];
            count=Math.max(count,cur);
            if(cur<=0) cur=0;
        }
        return count;
    }
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值