【代码随想录算法训练营第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

相关推荐
谈笑也风生26 分钟前
经典算法题之子集(四)
算法
mit6.82442 分钟前
划分dp+滑窗+前缀和|deque优化
算法
Pluchon1 小时前
硅基计划6.0 柒 JavaEE 浅谈JVM&GC垃圾回收
java·jvm·数据结构·java-ee·gc
Zach_yuan1 小时前
算法1111
算法
不穿格子的程序员2 小时前
从零开始刷算法——二分-搜索旋转排序数组
数据结构·算法
做怪小疯子2 小时前
LeetCode 热题 100——哈希——最长连续序列
算法·leetcode·哈希算法
做怪小疯子2 小时前
LeetCode 热题 100——双指针——三数之和
算法·leetcode·职场和发展
高山上有一只小老虎3 小时前
等差数列前n项的和
java·算法
sin_hielo3 小时前
leetcode 2536
数据结构·算法·leetcode
flashlight_hi3 小时前
LeetCode 分类刷题:203. 移除链表元素
算法·leetcode·链表