【算法刷题day32】Leetcode:122. 买卖股票的最佳时机 II、55. 跳跃游戏、45. 跳跃游戏 II

文章目录

草稿图网站
java的Deque

Leetcode 122. 买卖股票的最佳时机 II

题目: 122. 买卖股票的最佳时机 II
解析: 代码随想录解析

解题思路

记录当前的购入金额,当上一次卖出金额收益高于这次的卖出金额时,卖出上次,这次的记为购入金额。(没用到贪心)

代码

java 复制代码
class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;
        int purchase = prices[0];
        int sell = prices[0];
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] < sell) {
                profit += (sell - purchase);
                purchase = prices[i];
            }
            sell = prices[i];
        }
        if (sell > purchase)
            profit += (sell - purchase);
        return profit;
    }
}

//贪心(今天卖了赚钱就卖,卖了亏本就不卖)
class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;
        for (int i = 1; i < prices.length; i++) {
            profit += Math.max(prices[i] - prices[i-1], 0);
        }
        return profit;
    }
}

总结

贪心算法代码量少阿

Leetcode 55. 跳跃游戏

题目: 55. 跳跃游戏
解析: 代码随想录解析

解题思路

遍历所有到cover的元素能覆盖到的范围,如果能大于等于最后一个元素,则返回true

代码

java 复制代码
class Solution {
    public boolean canJump(int[] nums) {
        int cover = 0;
        if (nums.length == 1)
            return true;
        for (int i = 0; i <= cover; i++) {
            cover = Math.max(i + nums[i], cover);
            if (cover >= nums.length - 1)
                return true;
        }
        return false;
    }
}

总结

暂无

Leetcode 45. 跳跃游戏 II

题目: 45. 跳跃游戏 II
解析: 代码随想录解析

解题思路

每次更新下一轮覆盖的最大范围。当走完当前覆盖范围的时候,step++。

代码

java 复制代码
class Solution {
    public int jump(int[] nums) {
        if (nums.length == 1) return 0;
        int step = 0;
        int curCover = 0;
        int nextCover = 0;
        for (int i = 0; i < nums.length; i++) {
            nextCover = Math.max(nextCover, i + nums[i]);
            if (i == curCover) {
                step++;
                curCover = nextCover;
                if (curCover >= nums.length - 1) break;
            }
        }
        return step;
    }
}

总结

暂无

相关推荐
用户979984807184 小时前
200 行代码写一个能跑的 AI Agent:不依赖任何框架,只靠 tool-calling 原理
算法
threerocks4 小时前
【Muse实战】X 流量作战室搭建保姆级教程 - 拥有你自己的运营团队
算法
GreenTea4 小时前
深度拆解 ScienceBuddy:如何用“双层递归自进化”构建高可靠科研 Agent Harness
前端·后端·算法
花椒技术4 小时前
2.46 秒生成 5 秒视频:拆解 H3 Max 的模型、推理栈与硬件协同
算法·音视频开发·视频编码
vivo互联网技术4 小时前
ART:妆容迁移框架,重新定义高保真妆容迁移 | ECCV 2026
人工智能·算法·图像识别
用户0441440924494 小时前
卫星信号模拟器里的四个坐标转换公式
算法
橘和柠4 小时前
阿里 open-code-review (AI代码审查工具)实战:安装、四层规则链、自定义规则格式与实测避坑
算法·面试
得物技术4 小时前
别再只卷向量检索了,得物交易搜索如何用“生成式”实现召回范式跃迁?
人工智能·算法·llm
罗西的思考4 小时前
[Agent Memory / 强化学习] MemPO源码学习笔记 ---(4)--- Rollout实现细节
人工智能·算法
罗西的思考5 小时前
机器人 / 物理 Agent Harness 综合分析与对比:从「更强的模型」到「更好的系统」
人工智能·算法·机器学习