day23 贪心算法 part01

问题1:分发饼干

题目:

455. 分发饼干 - 力扣(LeetCode)

思路:

代码:

java 复制代码
class Solution {
    public int findContentChildren(int[] g, int[] s) {
             /*
        step1 : 找到胃口最小的小孩儿
        step2 : 喂饼干
         */
        int res = 0;
        Arrays.sort(g);
        Arrays.sort(s);
        int i = 0;
        int j = 0;
        while (i < g.length && j < s.length) {
            if (g[i] <= s[j]) {
                j++;
                i++;
                res++;
            } else {
                j++;
            }

        }
        return res;
    }
}
问题2: 摆动序列

题目:

376. 摆动序列 - 力扣(LeetCode)

思路:

三种情况 去看待 考虑到平坡

代码:

java 复制代码
class Solution {
    public int wiggleMaxLength(int[] nums) {
           /*
        贪心的策略就是删除以下三种情况
        1. 上下坡有平坡
        2. 首尾元素
        3. 单调坡有平坡
         */
        if (nums.length == 1) return 1;
        if (nums.length == 2 && nums[0] == nums[1]){return 1;}
        if (nums.length == 2 && nums[0] != nums[1]){return 2;}
        int prediff = 0;
        int curdiff = 0;
        int res = 1;
        for (int i = 0; i < nums.length-1; i++){
            curdiff = nums[i+1] - nums[i];
            if (prediff >= 0 && curdiff < 0 || prediff <= 0 && curdiff > 0){
                prediff = curdiff;
                res ++;
            }
        }
        return res;
    }
}
问题3:最大子序和

题目:

53. 最大子数组和 - 力扣(LeetCode)

思路:

局部到整体 深有体会

代码:

java 复制代码
class Solution {
    public int maxSubArray(int[] nums) {
   if (nums.length == 1){
            return nums[0];
        }
        int sum = Integer.MIN_VALUE;
        int count = 0;
        for (int i = 0; i < nums.length; i++){
            count += nums[i];
            sum = Math.max(sum, count); // 取区间累计的最大值(相当于不断确定最大子序终止位置)
            if (count <= 0){
                count = 0; // 相当于重置最大子序起始位置,因为遇到负数一定是拉低总和
            }
        }
        return sum;
    }
}
相关推荐
BothSavage8 小时前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn8 小时前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法
烬羽9 小时前
字符串算法入门:从反转字符串到回文判断,面试不再慌
算法·面试
先吃饱再说1 天前
判断回文字符串,从一行代码到双指针优化
算法
黄敬峰1 天前
深入理解算法核心:从递归思想、数组扁平化到快速排序
算法
得物技术1 天前
从狂野代码到按目标生产:得物推荐 AI Harness 的工程化实践|AICon 演讲整理
人工智能·算法·架构
AI小老六1 天前
SkillOpt 架构拆解:把 Skill 文本当参数,用执行轨迹训练 Agent
后端·算法·ai编程
胡萝卜术1 天前
从“分数打架”到“排名投票”:为什么你的ChatBI必须用RRF?
算法·设计模式·面试
Asize1 天前
初识DFS 与 BFS:递归、队列与图遍历
算法