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

相关推荐
TAN-90°-几秒前
Deep Learning for Computer Vision——Training CNNs and CNN Architectures
人工智能·深度学习·神经网络·算法·机器学习·计算机视觉·cnn
0x3F(小茶)1 分钟前
Tokenization(分词算法):一切大语言模型的地基
人工智能·算法·语言模型
Keven_114 分钟前
算法札记:利用floyd判环算法优化SPFA判负环算法
算法·spfa判负环
ambition202423 小时前
操作系统同步:读者-写者问题与读写公平法详解(附每个 PV 操作含义)
linux·开发语言·数据结构·unix
mCell8 小时前
Lua 编程入门:从基础语法到元表
javascript·算法·lua
wuyk55510 小时前
98.C语言易混难点:字符数组与字符串指针的底层差异
c语言·开发语言·c++·stm32·嵌入式硬件·算法
峥无11 小时前
从0到1手撕红黑树:封装实现 my_map 与 my_set(SGI-STL 源码级深度解析)
开发语言·c++·笔记·算法·stl
不会代码的小猴11 小时前
3. 控件学习1
开发语言·c++·笔记·qt·算法
疯狂打码的少年13 小时前
【数据结构】图的存储结构:邻接矩阵与邻接表
数据结构·笔记