算法笔记|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;
    }
}
相关推荐
岁忧1 小时前
(LeetCode 面试经典 150 题 ) 11. 盛最多水的容器 (贪心+双指针)
java·c++·算法·leetcode·面试·go
chao_7891 小时前
二分查找篇——搜索旋转排序数组【LeetCode】两次二分查找
开发语言·数据结构·python·算法·leetcode
陈洪奇2 小时前
注册中心学习笔记整理
笔记·学习
秋说3 小时前
【PTA数据结构 | C语言版】一元多项式求导
c语言·数据结构·算法
Maybyy3 小时前
力扣61.旋转链表
算法·leetcode·链表
兴趣使然_5 小时前
【笔记】使用 html 创建网址快捷方式
笔记·html·js
卡卡卡卡罗特5 小时前
每日mysql
数据结构·算法
chao_7896 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找
aramae6 小时前
C++ -- STL -- vector
开发语言·c++·笔记·后端·visual studio
lifallen7 小时前
Paimon 原子提交实现
java·大数据·数据结构·数据库·后端·算法