Day32 贪心算法 part02 122. 买卖股票的最佳时机 II 55. 跳跃游戏 45. 跳跃游戏 II

贪心算法 part02 122. 买卖股票的最佳时机 II 55. 跳跃游戏 45. 跳跃游戏 II

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

思路:计算每天的利润,利润如果为正,加到结果中去

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

55. 跳跃游戏

cpp 复制代码
class Solution {
private:
    int cover =0;
public:
    bool canJump(vector<int>& nums) {
        if(nums.size()==1) return true;//一个元素直接返回true
        for(int i =0;i<=cover;i++){
            cover = max(i+nums[i],cover); //动态更新覆盖范围
            if(cover>=nums.size()-1) return true;
        }
        return false;
    }
};

45. 跳跃游戏 II

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;
    }
};
相关推荐
雾月558 分钟前
LeetCode 1292 元素和小于等于阈值的正方形的最大边长
java·数据结构·算法·leetcode·职场和发展
hnlucky13 分钟前
redis 数据类型新手练习系列——Hash类型
数据库·redis·学习·哈希算法
Invinciblenuonuo22 分钟前
FreeRTOS学习笔记【10】-----任务上下文切换
笔记·学习
好奇龙猫23 分钟前
日语学习-日语知识点小记-构建基础-JLPT-N4阶段(11): てあります。
学习
Pasregret27 分钟前
访问者模式:分离数据结构与操作的设计模式
数据结构·设计模式·访问者模式
OpenC++37 分钟前
【C++QT】Buttons 按钮控件详解
c++·经验分享·qt·leetcode·microsoft
2501_915373881 小时前
Node.js 学习入门指南
学习·node.js
YuforiaCode1 小时前
第十二届蓝桥杯 2021 C/C++组 直线
c语言·c++·蓝桥杯
绵绵细雨中的乡音2 小时前
Linux进程学习【基本认知】
linux·运维·学习
知来者逆2 小时前
计算机视觉——速度与精度的完美结合的实时目标检测算法RF-DETR详解
图像处理·人工智能·深度学习·算法·目标检测·计算机视觉·rf-detr