day32||第八章 贪心算法 part02● 122.买卖股票的最佳时机II ● 55. 跳跃游戏 ● 45.跳跃游戏II

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

发现一个评论的思路,也挺不错的:

可以把股票的价格波动画出来,单调上升就是盈利,题解就是每一段单调上升的总和,

跟讲解的思路类似。

就是把连续几天的利润分解,分解成一天一天的利润。

复制代码
class Solution {
    public int maxProfit(int[] prices) {
        int res = 0;
        for(int i = 1;i<prices.length;i++){
            res += Math.max(0,prices[i]-prices[i-1]) ;
        }
        return res;
    }
}

● 55. 跳跃游戏

cover是覆盖范围

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

● 45.跳跃游戏II

cur和next是下标!!!

复制代码
class Solution {
    public int jump(int[] nums) {
        if(nums.length==1) return 0;
        int cur =0,next=0;
        int res = 0;
        for(int i = 0;i<nums.length;i++){
            next = Math.max(i+nums[i],next);
            if(i==cur){
                res++;
                cur = next;
                if(next>=nums.length-1){
                    break;
                }
            }
        }
        return res;
    }
}
相关推荐
.道阻且长.4 小时前
2.LeetCode算法习题讲解--双指针--复写零
算法·leetcode·职场和发展
To_OC6 小时前
LC 438 找到所有字母异位词:暴力超时后,我靠滑动窗口一招搞定
javascript·算法·leetcode
Forever Nore9 小时前
学完C语言力扣第一题做不来正常吗
数据结构·算法
hansang_IR9 小时前
【题解】LC:倍增 / 区间并查集(Range Parallel Unionfind)
c++·算法·并查集
Tisfy11 小时前
LeetCode 3731.找出缺失的元素:哈希 / 排序
算法·leetcode·哈希算法·排序·哈希表
lucas_AI11 小时前
Q-CueGraph:你的多模态大模型会 zoom,但真的知道该看哪儿吗?
人工智能·算法
kaixin_啊啊11 小时前
test_机器学习算法学习
学习·算法·机器学习
liulilittle11 小时前
MOE路由:路由(logits: top-k/8)
c++·人工智能·算法·机器学习·llm
旖旎夜光11 小时前
LeetCode 11:盛最多水的容器(双指针问题) —— 题解
数据结构·c++·算法·leetcode·双指针