当前位置:   article > 正文

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

【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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/221607
推荐阅读
相关标签
  

闽ICP备14008679号