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

总结

暂无

相关推荐
心扬几秒前
python数据结构和算法(5)
数据结构·python·算法
gogoMark24 分钟前
FaceFusion 技术深度剖析:核心算法与实现机制揭秘
算法
倔强的石头_1 小时前
【数据结构与算法 经典例题】使用队列实现栈(图文详解)
后端·算法
黑色的山岗在沉睡1 小时前
P1216 [IOI 1994] 数字三角形 Number Triangles
算法·动态规划
青山是哪个青山2 小时前
递归,回溯,DFS,Floodfill,记忆化搜索
算法·深度优先
一块plus2 小时前
参与、拥有、共创:Web3 游戏开启玩家共建时代
算法·程序员·架构
倔强的石头_2 小时前
【数据结构与算法】插入排序:原理、实现与分析
算法
倔强的石头_2 小时前
【数据结构与算法】希尔排序:基于插入排序的高效排序算法
后端·算法
Shaun_青璇3 小时前
CPP基础(2)
开发语言·c++·算法
红糖生姜3 小时前
字符串|数组|计算常见函数整理-竞赛专用(从比赛真题中总结的,持续更新中)
c++·算法