算法训练营第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;
    }
};
相关推荐
humors22133 分钟前
支付宝游戏频道《灵画师》体验
游戏·介绍·体验·攻略·灵画师·试玩
AndrewHZ1 小时前
【LLM技术全景】阶段总结:技术原理篇核心知识回顾
人工智能·深度学习·算法·语言模型·大模型·llm·芯片开发
小星星闪亮登场2 小时前
2026萌新联赛第三场-- (郑州轻工业大学)
数据结构·c++·经验分享·算法·贪心算法·排序算法·深度优先
冻柠檬飞冰走茶2 小时前
PTA基础编程题目集 7-8超速判断(C++语言实现)
开发语言·数据结构·c++·算法
玖玥拾3 小时前
LeetCode 88 合并两个有序数组
算法·leetcode
数据皮皮侠AI3 小时前
上市公司数字供应链金融指数(2010-2024)
大数据·人工智能·算法
小程故事多_804 小时前
用GRPO算法重塑多智能体系统,从原理落地到复杂任务规划实战
人工智能·算法
HMS Core4 小时前
基于人体骨骼点识别与跟踪,实现低时延体感游戏
游戏·华为·harmonyos
Hi李耶4 小时前
【LeetCode】541.反转字符串 II
算法·leetcode·职场和发展
shylyly_4 小时前
104.二叉树的最大深度
数据结构·算法·104.二叉树的最大深度