算法训练营第32天|LeetCode 122.买卖股票的最佳时机Ⅱ 55.跳跃游戏 45.跳跃游戏Ⅱ

LeetCode 122.买卖股票的最佳时机Ⅱ

题目链接:

[LeetCode 122.买卖股票的最佳时机Ⅱ]( "LeetCode 122.买卖股票的最佳时机Ⅱ")

解题思路:

把利润拆成,后一天减前一天的累加和。如何累加和大于0,则加到sum里,否则则不要。

代码:

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

LeetCode 55.跳跃游戏

题目链接:

LeetCode 55.跳跃游戏

解题思路:

看能跳跃的覆盖范围,如果覆盖范围大于当前数组长度减一,则返回true。

代码:

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(cover,i+nums[i]);
            if( cover>=nums.size()-1){
                return true;
                break;
            }
        }
        return false;
    }
};

LeetCode 45.跳跃游戏Ⅱ

题目链接:

LeetCode 45.跳跃游戏Ⅱ

解题思路:

维护两个值,一个是当前覆盖范围一个是下一步的覆盖范围。当i遍历完当前覆盖范围时,将当前覆盖范围的值更新为下一步最大能覆盖到的范围。

代码:

cpp 复制代码
class Solution {
public:
    int jump(vector<int>& nums) {
        int cur = 0;
        int next = 0;
        int result = 0;
        for(int i= 0;i<nums.size();i++){
            next = max(next,i+nums[i]);
            if(cur == i){
                if(cur!=nums.size()-1){
                    cur = next;
                    result++;
                }
                else break;
            }
        }
        return result;
    }
};
相关推荐
ADDDDDD_Trouvaille11 分钟前
2026.2.13——OJ75-77题
c++·算法
重生之后端学习18 分钟前
230. 二叉搜索树中第 K 小的元素
java·数据结构·算法·深度优先
近津薪荼19 分钟前
dfs专题7—— 全排列
c++·学习·算法·深度优先
你的冰西瓜23 分钟前
C++ STL算法——非修改序列算法
开发语言·c++·算法·stl
闻缺陷则喜何志丹27 分钟前
P12275 [蓝桥杯 2024 国 Python B] 工厂|普及+
c++·算法·蓝桥杯·洛谷
宝贝儿好34 分钟前
【强化学习】第九章:基于Action-Critic框架的强化学习
人工智能·python·深度学习·算法·动态规划
laplace012339 分钟前
KL 散度1
人工智能·算法·agent·qwen
白中白121381 小时前
算法题-14
数据结构·算法·leetcode
2501_901147831 小时前
打家劫舍问题的动态规划解法与性能优化笔记
笔记·算法·动态规划
plus4s2 小时前
2月13日(73-75题)
数据结构·c++·算法