代码随想录算法训练营第三十二天| 122.买卖股票的最佳时机II、55.跳跃游戏 、45.跳跃游戏II

代码随想录算法训练营第三十二天| 122.买卖股票的最佳时机II、55.跳跃游戏 、45.跳跃游戏II

题目

122.买卖股票的最佳时机II

给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。

在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。

返回 你能获得的 最大 利润

python 复制代码
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        sum_ = 0
        for i in range(1, len(prices)):
            lirun = prices[i] - prices[i - 1]
            if lirun > 0:
                sum_ += lirun
        return sum_

题目

55.跳跃游戏

给你一个非负整数数组 nums ,你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。

判断你是否能够到达最后一个下标,如果可以,返回 true ;否则,返回 false

python 复制代码
class Solution:
    def canJump(self, nums: List[int]) -> bool:
        can_reach = [False] * len(nums)
        can_reach[0] = True
        for i in range(len(nums) - 1):
            if can_reach[i]:
                for j in range(nums[i]):
                    if i + j + 1 == len(nums):
                        return True
                    can_reach[i+j+1] = True
        return can_reach[len(nums) - 1]

题目

45.跳跃游戏II

给定一个长度为 n0 索引 整数数组 nums。初始位置为 nums[0]

每个元素 nums[i] 表示从索引 i 向前跳转的最大长度。换句话说,如果你在 nums[i] 处,你可以跳转到任意 nums[i + j] 处:

  • 0 <= j <= nums[i]
  • i + j < n

返回到达 nums[n - 1] 的最小跳跃次数。生成的测试用例可以到达 nums[n - 1]

python 复制代码
class Solution:
    def jump(self, nums: List[int]) -> int:
        step = 0
        if len(nums) < 2:
            return step
        cover_max = 0
        cur = 0
        while cur <= cover_max:
            for cur in range(cur, cover_max + 1):
                cover_max = max(cover_max, nums[cur] + cur)
                if cover_max >= len(nums) - 1:
                    return step + 1
            step += 1
相关推荐
测试仪器廖生1359025638518 分钟前
罗德与施瓦茨 FSP13频谱分析仪FSP30
网络·人工智能·算法
happymaker062621 分钟前
LeetCodeHot100——560.和为K的子数组
算法
dtq042438 分钟前
C语言刷题数组5,6(求平均值,求最大值)
c语言·数据结构·算法
郭梧悠1 小时前
Hash算法入门Hash冲突解决方案
算法·哈希算法
洛水水1 小时前
【力扣100题】81.寻找两个正序数组的中位数
数据结构·算法·leetcode
happymaker06262 小时前
LeetCodeHot100——155.最小栈
算法
洛水水2 小时前
【力扣100题】85.每日温度
算法·leetcode·职场和发展
Coder-magician2 小时前
《代码随想录》刷题打卡day15:二叉树part05
数据结构·c++·算法
Kurisu_红莉栖2 小时前
力扣56合并区间
算法·leetcode
德迅--文琪2 小时前
守护数字游戏乐园:解析DDoS攻击与德迅云安全游戏盾防护方案
游戏·ddos