算法训练营第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;
    }
};
相关推荐
CM莫问2 小时前
<论文>(微软)避免推荐域外物品:基于LLM的受限生成式推荐
人工智能·算法·大模型·推荐算法·受限生成
康谋自动驾驶3 小时前
康谋分享 | 自动驾驶仿真进入“标准时代”:aiSim全面对接ASAM OpenX
人工智能·科技·算法·机器学习·自动驾驶·汽车
C++ 老炮儿的技术栈4 小时前
什么是函数重载?为什么 C 不支持函数重载,而 C++能支持函数重载?
c语言·开发语言·c++·qt·算法
yychen_java5 小时前
R-tree详解
java·算法·r-tree
MarkHard1235 小时前
Leetcode (力扣)做题记录 hot100(62,64,287,108)
算法·leetcode·职场和发展
一只鱼^_6 小时前
牛客练习赛138(首篇万字题解???)
数据结构·c++·算法·贪心算法·动态规划·广度优先·图搜索算法
一只码代码的章鱼6 小时前
Spring的 @Validate注解详细分析
前端·spring boot·算法
邹诗钰-电子信息工程6 小时前
嵌入式自学第二十一天(5.14)
java·开发语言·算法
↣life♚7 小时前
从SAM看交互式分割与可提示分割的区别与联系:Interactive Segmentation & Promptable Segmentation
人工智能·深度学习·算法·sam·分割·交互式分割
zqh176736464697 小时前
2025年阿里云ACP人工智能高级工程师认证模拟试题(附答案解析)
人工智能·算法·阿里云·人工智能工程师·阿里云acp·阿里云认证·acp人工智能