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

相关推荐
我搞slam9 分钟前
有效的括号--leetcode
linux·算法·leetcode
Yupureki1 小时前
从零开始的C++学习生活 19:C++复习课(5.4w字全解析)
c语言·数据结构·c++·学习·1024程序员节
ゞ 正在缓冲99%…2 小时前
leetcode1312.让字符串成为回文串的最少插入次数
数据结构·算法·leetcode·动态规划·记忆化搜索
七夜zippoe2 小时前
Rust `std::iter` 深度解析:`Iterator` Trait、适配器与性能
开发语言·算法·rust
寂静山林2 小时前
UVa 1464 Traffic Real Time Query System
算法
laocooon5238578862 小时前
寻找使a×b=c成立的最小进制数(2-16进制)
数据结构·算法
YY_TJJ2 小时前
算法题——图论
算法·深度优先·图论
默默的流星雨2 小时前
TARJAN相关
c++·算法·深度优先·图论
JJJJ_iii3 小时前
【机器学习11】决策树进阶、随机森林、XGBoost、模型对比
人工智能·python·神经网络·算法·决策树·随机森林·机器学习
loong_XL4 小时前
AC自动机算法-字符串搜索算法:敏感词检测
开发语言·算法·c#