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

总结

暂无

相关推荐
charley.layabox2 小时前
8月1日ChinaJoy酒会 | 游戏出海高端私享局 | 平台 × 发行 × 投资 × 研发精英畅饮畅聊
人工智能·游戏
今天背单词了吗9806 小时前
算法学习笔记:19.牛顿迭代法——从原理到实战,涵盖 LeetCode 与考研 408 例题
笔记·学习·算法·牛顿迭代法
jdlxx_dongfangxing7 小时前
进制转换算法详解及应用
算法
why技术8 小时前
也是出息了,业务代码里面也用上算法了。
java·后端·算法
2501_922895588 小时前
字符函数和字符串函数(下)- 暴力匹配算法
算法
IT信息技术学习圈9 小时前
算法核心知识复习:排序算法对比 + 递归与递推深度解析(根据GESP四级题目总结)
算法·排序算法
愚润求学9 小时前
【动态规划】01背包问题
c++·算法·leetcode·动态规划
会唱歌的小黄李10 小时前
【算法】贪心算法入门
算法·贪心算法
轻语呢喃10 小时前
每日LeetCode : 两数相加--链表操作与进位的经典处理
javascript·算法
钢铁男儿11 小时前
C# 接口(接口可以继承接口)
java·算法·c#