Day 31 贪心算法 part02

Day 31 贪心算法 part02

3道题目
122. 买卖股票的最佳时机 II
55. 跳跃游戏
45. 跳跃游戏 II

解题理解

122

这里有一个数学思维很巧妙,即可以将每天的利润拆成之前的利润总和,第三天的利润=prices[3] - prices[0]=(prices[3] - prices[2]) + (prices[2] - prices[1]) + (prices[1] - prices[0]),这样会组成一个长度-1的新数组,数组中寸的就是每天对前一天的利润,还有一个非常符合贪心算法的特点是,只累加新数组中的整数,就能得到最后的最大利润。但能这么做的原因是因为可以在同一天既买又卖。

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0
        for i in range(1, len(prices)):
            profit += max(prices[i] - prices[i - 1], 0)
        return profit

55

可以把最大长度转化为当前下标所覆盖的最远距离。

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        if len(nums) == 1:
            return True
        maxfield = i = 0
        while i <= maxfield:
            maxfield = max(i + nums[i], maxfield)
            if maxfield >= len(nums) - 1:
                return True
            i += 1
        return False

45

这道题跟上一题很像,但思路很不好想,即使看了题解也觉得非常抽象。简单来说就是,当下标来到当前下标的覆盖极限距离时,需要计算下一次的覆盖距离,此时就要将步数+1,若在到达极限距离之前遍历完了整个数组,将结果输出。

class Solution:
    def jump(self, nums: List[int]) -> int:
        step = 0
        if len(nums) == 1:
            return 0
        nextcover = curcover = i = 0
        while i <= len(nums):
            nextcover = max(i + nums[i], nextcover)
            if i == curcover:
                step += 1
                //步数要在这里+1,说明走到上一次的极限覆盖距离都没法走到头,所以需要看下一次覆盖距离到哪里
                curcover = nextcover
                if nextcover >= len(nums) - 1:
                    break
            i += 1
        return step
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值