算法笔记|Day23贪心算法

算法笔记|Day23贪心算法

  • [☆☆☆☆☆leetcode 455.分发饼干](#☆☆☆☆☆leetcode 455.分发饼干)
  • [☆☆☆☆☆leetcode 376. 摆动序列](#☆☆☆☆☆leetcode 376. 摆动序列)
  • [☆☆☆☆☆leetcode 53. 最大子序和](#☆☆☆☆☆leetcode 53. 最大子序和)

☆☆☆☆☆leetcode 455.分发饼干

题目链接:leetcode 455.分发饼干

题目分析

优先考虑饼干,先喂饱小胃口:若饼干不足以喂孩子,则换下一块饼干;若能喂,则count加一,换下一块饼干喂下一个孩子。

代码

java 复制代码
class Solution {
    public int findContentChildren(int[] kid, int[] biscuit) {
        Arrays.sort(kid);
        Arrays.sort(biscuit);
        int count=0;
        int i=0;
        for(int j=0;i<kid.length&&j<biscuit.length;j++){
            if(biscuit[j]>=kid[i]){
                count++;
                i++;
            }
        }
        return count;
    }
}

☆☆☆☆☆leetcode 376. 摆动序列

题目链接:leetcode 376. 摆动序列

题目分析

此题需要计算前一个差值preDiff和当前差值curDiff,若一正一负(preDiff>0&&curDiff<0||preDiff<0&&curDiff>0)则出现摆动count加一。在此基础上,还应考虑以下三种情况:①上下坡中有平坡,需要在一侧补充等于0的情况,改为preDiff>=0和preDiff<=0;②数组首尾两端,考虑只有两个元素的情况,结果应为2,可以假设前一个preDiff为0,过程中加一,结尾自动加一,也就是count初始值为1,遍历是不考虑最后一个元素;③单调坡中有平坡只需要在这个坡度摆动变化的时候,更新preDiff就行。

代码

java 复制代码
class Solution {
    public int wiggleMaxLength(int[] nums) {
        int count=1;
        int preDiff=0,curDiff=0;
        for(int i=0;i<nums.length-1;i++){
            curDiff=nums[i+1]-nums[i];
            if(preDiff>=0&&curDiff<0||preDiff<=0&&curDiff>0){
                count++;
                preDiff=curDiff;
            }
        }
        return count;
    }
}

☆☆☆☆☆leetcode 53. 最大子序和

题目链接:leetcode 53. 最大子序和

题目分析

依次遍历每个元素,并求得连续元素和,若比当前res值大,则赋给res。若当前连续元素和小于0,则重新计算元素和,sum赋值为0。

代码

java 复制代码
class Solution {
    public int maxSubArray(int[] nums) {
        int res=Integer.MIN_VALUE,sum=0;
        for(int i=0;i<nums.length;i++){
            sum+=nums[i];
            res=sum>res?sum:res;
            if(sum<0)
                sum=0;
        }
        return res;
    }
}
相关推荐
Answer1st5 小时前
【嵌入式模块】UART通信模块
笔记
和侧6 小时前
离子注入后为什么必须配套退火工艺?
笔记·学习
生态学者6 小时前
Global Change Biology | 森林越“步调一致”,反而越怕干旱?树木生长与叶片活动的同步之谜
大数据·人工智能·算法·r语言·微信公众平台
lsswear7 小时前
Agent 框架新手入门与实战部署指南
大数据·人工智能·算法
Data analyse4568 小时前
rnweb 回放数据量太大怎么办?分片存储与断点续传的实现思路
前端·网络·算法·数据分析
TheBlackHoleLab10 小时前
【Vulnhub系列】DarkHole1: 渗透测试笔记,没有踩渗透的坑,却踩到了虚拟机平台的坑,人生处处是大坑
笔记·vulnhub·easy·darkhole1
Navigator_Z10 小时前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
ACP广源盛1392462567310 小时前
硬件选型笔记:GSV2231@ACP,DP1.4 MST 一进三出多屏扩展方案评估
笔记·硬件架构·视频·mst·国产芯片
Nil20810 小时前
leetcode 64最小路径和
算法·leetcode·职场和发展
光影少年10 小时前
AI Agent、自动化与未来工作
人工智能·算法·架构