【leetcode刷刷】122.买卖股票的最佳时机II 、55. 跳跃游戏 、45.跳跃游戏II

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

  1. 这个贪心还比较好想
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # 波谷和波峰的差。后一个减前一个,如果大于0,就加入利润
        max_profit = 0
        for i in range(1, len(prices)):
            if prices[i] - prices[i-1] > 0:
                max_profit += prices[i] - prices[i-1]
        return max_profit

55. 跳跃游戏

  1. 这个贪心不是很好想,但是看了题解之后,写还是容易的
class Solution:
    def canJump(self, nums: List[int]) -> bool:
        max_index = 0
        for i in range(len(nums)):
            if max_index >= len(nums) - 1: return True
            if max_index >= i:
                max_index = max(i+nums[i], max_index)
            else:
                return False
        return True

45.跳跃游戏II

  1. 没刷过完全想不到again
class Solution:
    def jump(self, nums: List[int]) -> int:
        if len(nums) == 1:
            return 0
        
        cur_distance = 0  # 当前覆盖最远距离下标
        ans = 0  # 记录走的最大步数
        next_distance = 0  # 下一步覆盖最远距离下标

        # 需要计算最小跳跃次数。贪心的话,依然是每次选最大的。
        for i in range(len(nums)):
            next_distance = max(i+nums[i], next_distance)
            if i == cur_distance:
                ans += 1
                cur_distance = next_distance
                if next_distance >= len(nums) -1: return ans
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值