【算法刷题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;
    }
}

总结

暂无

相关推荐
da_vinci_x23 分钟前
在Substance Designer里“预演”你的游戏着色器(Shader)
人工智能·游戏·技术美术·着色器·游戏策划·游戏美术·substance designer
reddingtons26 分钟前
ZBrush细节烘焙全“糊”了?Painter“平均法线”+“偏斜贴图”的“无笼”烘焙管线
游戏·设计师·贴图·技术美术·substance painter·游戏美术·zbrush
ゞ 正在缓冲99%…1 小时前
leetcode1312.让字符串成为回文串的最少插入次数
数据结构·算法·leetcode·动态规划·记忆化搜索
七夜zippoe1 小时前
Rust `std::iter` 深度解析:`Iterator` Trait、适配器与性能
开发语言·算法·rust
寂静山林2 小时前
UVa 1464 Traffic Real Time Query System
算法
laocooon5238578862 小时前
寻找使a×b=c成立的最小进制数(2-16进制)
数据结构·算法
YY_TJJ2 小时前
算法题——图论
算法·深度优先·图论
默默的流星雨2 小时前
TARJAN相关
c++·算法·深度优先·图论
JJJJ_iii3 小时前
【机器学习11】决策树进阶、随机森林、XGBoost、模型对比
人工智能·python·神经网络·算法·决策树·随机森林·机器学习
别学LeetCode3 小时前
#leetcode#
leetcode