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

相关推荐
jllllyuz32 分钟前
MATLAB 蒙特卡洛排队等待模拟程序
数据结构·matlab
自我意识的多元宇宙43 分钟前
树、森林——树、森林与二叉树的转换(森林转换为二叉树)
数据结构
海清河晏1111 小时前
数据结构 | 双循环链表
数据结构·链表
workflower1 小时前
机器人应用-楼宇室内巡逻
大数据·人工智能·算法·microsoft·机器人·动态规划·享元模式
ZPC82101 小时前
fanuc 机器人通过PR寄存器实现轨迹控制
人工智能·算法·计算机视觉·机器人
py有趣1 小时前
力扣热门100题之编辑距离
数据结构·算法·leetcode
Wave8451 小时前
C++继承详解
开发语言·c++·算法
睡觉就不困鸭2 小时前
第9天 两数之和
算法·哈希算法·散列表
贾斯汀玛尔斯2 小时前
每天学一个算法--动态规划(Dynamic Programming, DP)
算法·动态规划
水木流年追梦2 小时前
CodeTop 热门题目汇总hot300题
算法·leetcode·职场和发展