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;
    }
};
相关推荐
To_OC2 小时前
LC 51 N 皇后:我以为难的是回溯,结果栽在了对角线下标
javascript·算法·leetcode
2401_841495642 小时前
【操作系统】进程同步与互斥实验报告
c++·算法·操作系统·进程·并发·同步·互斥
fqbqrr2 小时前
2607C++,soui与安卓
c++·soui
a1117765 小时前
2FA 验证码生成器(github登录验证 app)
笔记·学习
我的xiaodoujiao6 小时前
API 接口自动化测试详细图文教程学习系列32--Allure测试报告2
python·学习·测试工具·pytest
fqbqrr6 小时前
2607C++,使用微软detours勾挂工具
c++
爱刷碗的苏泓舒6 小时前
PPP-AR 中的参考星选取:数学原理、评价指标与切换处理
算法·gnss·模糊度固定·ppp-ar·星间单差·参考星·卫星端偏差
你想知道什么?7 小时前
线性回归-学习笔记
笔记·学习·线性回归
鱼毓屿御7 小时前
从「只会聊」到「边想边做」的跃迁
前端·学习·react.js