算法训练营第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;
    }
};
相关推荐
dazzle30 分钟前
机器学习算法原理与实践-入门(三):使用数学方法实现KNN
人工智能·算法·机器学习
那个村的李富贵31 分钟前
智能炼金术:CANN加速的新材料AI设计系统
人工智能·算法·aigc·cann
ujainu33 分钟前
Flutter + OpenHarmony 实现经典打砖块游戏开发实战—— 物理反弹、碰撞检测与关卡系统
flutter·游戏·openharmony·arkanoid·breakout
张张努力变强1 小时前
C++ STL string 类:常用接口 + auto + 范围 for全攻略,字符串操作效率拉满
开发语言·数据结构·c++·算法·stl
万岳科技系统开发1 小时前
食堂采购系统源码库存扣减算法与并发控制实现详解
java·前端·数据库·算法
张登杰踩1 小时前
MCR ALS 多元曲线分辨算法详解
算法
YuTaoShao1 小时前
【LeetCode 每日一题】3634. 使数组平衡的最少移除数目——(解法一)排序+滑动窗口
算法·leetcode·排序算法
波波0071 小时前
每日一题:.NET 的 GC是如何分代工作的?
算法·.net·gc
风暴之零1 小时前
变点检测算法PELT
算法
深鱼~1 小时前
视觉算法性能翻倍:ops-cv经典算子的昇腾适配指南
算法·cann