算法训练Day28 | ● 122.买卖股票的最佳时机II ● 55. 跳跃游戏 ● 45.跳跃游戏II

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

cpp 复制代码
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        vector<int> dp(2,0);
        dp[0] = -prices[0];
        for(int i=1; i<prices.size(); i++){
            dp[0] = max(dp[0], dp[1]-prices[i]);
            dp[1] = max(dp[1], prices[i]+dp[0]);
        }
        return dp[1];
    }
};

参考文章:代码随想录- 122.买卖股票的最佳时机II

55. 跳跃游戏

cpp 复制代码
class Solution {
public:
    bool canJump(vector<int>& nums) {
        int cover = 0;
        for(int i=0; i<=cover; i++){
            
            if(i+nums[i]>cover){
                cover = i+nums[i];
            }
            if(cover>=nums.size()-1) return true;
        }
        return false;

    }
};

参考文章:代码随想录-55. 跳跃游戏

45.跳跃游戏II

cpp 复制代码
class Solution {
public:
    int jump(vector<int>& nums) {
        if (nums.size() == 1) return 0;
        int cover = 0;
        int next_cover = 0;
        int count = 0;
        for(int i=0; i<=nums.size(); i++){
            
            if(i+nums[i]>next_cover){
                next_cover = i+nums[i];
            }
            if(i == cover){
                count++;
                cover = next_cover;
                if(next_cover>=nums.size()-1){
                    return count;
                }
                
                
                
            }
        }
        return -1;

    }
};

参考文章:代码随想录- 45.跳跃游戏II

相关推荐
未来之窗软件服务4 小时前
自己写算法(九)网页数字动画函数——东方仙盟化神期
前端·javascript·算法·仙盟创梦ide·东方仙盟·东方仙盟算法
豐儀麟阁贵4 小时前
基本数据类型
java·算法
乐迪信息6 小时前
乐迪信息:基于AI算法的煤矿作业人员安全规范智能监测与预警系统
大数据·人工智能·算法·安全·视觉检测·推荐算法
hsjkdhs7 小时前
C++之多层继承、多源继承、菱形继承
开发语言·c++·算法
立志成为大牛的小牛7 小时前
数据结构——十七、线索二叉树找前驱与后继(王道408)
数据结构·笔记·学习·程序人生·考研·算法
星空下的曙光7 小时前
Node.js crypto模块所有 API 详解 + 常用 API + 使用场景
算法·node.js·哈希算法
Algo-hx7 小时前
数据结构入门 (七):从“链接”到“分支” —— 初探树与二叉树
数据结构
小贾要学习8 小时前
【数据结构】C++实现红黑树
数据结构·c++
StarPrayers.9 小时前
旅行商问题(TSP)(2)(heuristics.py)(TSP 的两种贪心启发式算法实现)
前端·人工智能·python·算法·pycharm·启发式算法
爱吃橘的橘猫9 小时前
嵌入式系统与嵌入式 C 语言(2)
c语言·算法·嵌入式