Day 32 | 贪心算法02

54 阅读1分钟

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

def maxProfit(self, prices: List[int]) -> int:
    # 只能持有一股股票:
    # 相当于遍历不断寻找最大的差值
    mini = prices[0]
    maxi = prices[0]
    res = 0
    for i in range(1, len(prices)):
        # 其实最终利润是可以分解的
        if prices[i] - prices[i-1] > 0:
            res += (prices[i] - prices[i-1])
    
    return res

55. 跳跃游戏

贪心的方式是 获得能跳到的最大下标

def canJump(self, nums: List[int]) -> bool:
    j = 0
    n = len(nums)
    d = 0
    while j <= d:
        # 取最大覆盖范围            
        d = max(d, nums[j] + j)
        if d >= n - 1: 
            return True
        j += 1
    return False

45. 跳跃游戏 II

不断更新从后之前的最小位置

(复杂度较高)

def jump(self, nums: List[int]) -> int:
    end = len(nums) - 1
    count = 0
    while end > 0:
        # 可以达到end的最小位置
        for i in range(end,-1,-1):
            if i + nums[i] >= end:
                update = i
        count += 1
        end = update
    return count

从前往后的更新方式

# 贪心版本二
class Solution:
    def jump(self, nums: List[int]) -> int:
        if len(nums) == 1:
            return 0
        curDistance, nextDistance = 0, 0
        step = 0
        for i in range(len(nums)-1):
            nextDistance = max(nextDistance, nums[i]+i)
            if i == curDistance:
                curDistance = nextDistance
                step += 1
        return step

dp做法

(待补)