【代码随想录算法训练营第37期 第三十二天 | LeetCode122.买卖股票的最佳时机II、55. 跳跃游戏、45.跳跃游戏II】

代码随想录算法训练营第37期 第三十二天 | LeetCode122.买卖股票的最佳时机II、55. 跳跃游戏、45.跳跃游戏II


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

解题代码C++:

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

题目链接/文章讲解/视频讲解:
https://programmercarl.com/0122.买卖股票的最佳时机II.html



二、55. 跳跃游戏

解题代码C++:

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

题目链接/文章讲解/视频讲解:
https://programmercarl.com/0055.跳跃游戏.html



三、45.跳跃游戏II

解题代码C++:

cpp 复制代码
class Solution {
public:
    int jump(vector<int>& nums) {
        int curDistance = 0;    // 当前覆盖的最远距离下标
        int ans = 0;            // 记录走的最大步数
        int nextDistance = 0;   // 下一步覆盖的最远距离下标
        for (int i = 0; i < nums.size() - 1; i++) { // 注意这里是小于nums.size() - 1,这是关键所在
            nextDistance = max(nums[i] + i, nextDistance); // 更新下一步覆盖的最远距离下标
            if (i == curDistance) {                 // 遇到当前覆盖的最远距离下标
                curDistance = nextDistance;         // 更新当前覆盖的最远距离下标
                ans++;
            }
        }
        return ans;
    }
};

题目链接/文章讲解/视频讲解:
https://programmercarl.com/0045.跳跃游戏II.html

相关推荐
情怀姑娘8 分钟前
面试题---------------场景+算法
java·算法·mybatis
chbmvdd13 分钟前
week5题解
数据结构·c++·算法
用户120391129472615 分钟前
面试官最爱问的字符串反转:7种JavaScript实现方法详解
算法·面试
vir0223 分钟前
小齐的技能团队(dp)
数据结构·c++·算法·图论
Star在努力1 小时前
C语言复习八(2025.11.18)
c语言·算法·排序算法
南山安1 小时前
从反转字符串看透面试官的“内心戏”:你的算法思维到底怎么样?
javascript·算法·面试
雪不下1 小时前
计算机中的数学:概率(2)
算法
zs宝来了1 小时前
HOT100-二分查找类型题
算法
_w_z_j_1 小时前
数组中的最长连续子序列
数据结构·算法
地平线开发者1 小时前
征程 6E/M 计算平台部署指南
算法·自动驾驶