Day 31 贪心算法 part02

Day 31 贪心算法 part02

  • 解题理解
    • 122
    • 55
  • 45

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

你可能感兴趣的:(贪心算法,算法)