代码随想录算法训练营Day 32| 贪心算法 part02 | 122.买卖股票的最佳时机II、55. 跳跃游戏 、45.跳跃游戏II

代码随想录算法训练营Day 32| 贪心算法 part02 | 122.买卖股票的最佳时机II、55. 跳跃游戏 、45.跳跃游戏II



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

题目链接

一、贪心

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        # 贪心:收集每天的正利润
        result = 0
        for i in range(len(prices)-1):
            if (prices[i+1]-prices[i]>0):
                result += prices[i+1]-prices[i]
        return result

55. 跳跃游戏

题目链接

一、贪心

class Solution(object):
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        cover = 0
        i = 0
        # 当跳跃可实现
        while i <= cover and i < len(nums):
            cover = max(nums[i]+i,cover)
            i +=1
            # 如果在任何时刻 cover 能覆盖到数组末尾,函数立即返回 True
            if cover>=len(nums)-1:
                return True
        return False


45.跳跃游戏II

题目链接

一、贪心

class Solution(object):
    def jump(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        cur = 0
        next = 0
        result = 0

        if len(nums)==1:
            return 0
        for i in range(len(nums)):
            next = max(next,nums[i]+i)
            if cur == i:
                cur = next
                result += 1
                if cur >= len(nums) - 1:  # 当前覆盖最远距离达到数组末尾,不用再做ans++操作,直接结束
                    break
        return result
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值