122. 买卖股票的最佳时机 II
贪心算法
-
如果想到其实最终利润是可以分解的,那么本题就很容易了!
如何分解呢?
假如第0天买入,第3天卖出,那么利润为:prices[3] - prices[0]。
相当于(prices[3] - prices[2]) + (prices[2] - prices[1]) + (prices[1] - prices[0])。
此时就是把利润分解为每天为单位的维度,而不是从0天到第3天整体去考虑!
那么根据prices可以得到每天的利润序列:(prices[i] - prices[i - 1]).....(prices[1] - prices[0])
-
从图中可以发现,其实我们需要收集每天的正利润就可以,收集正利润的区间,就是股票买卖的区间,而我们只需要关注最终利润,不需要记录区间。
-
局部最优:收集每天的正利润,全局最优:求得最大利润。
# Time complexity: O(n)
# Space complexity: O(1)
class Solution:
def maxProfit(self, prices: List[int]) -> int:
result = 0
for i in range(1, len(prices)):
result += max(prices[i] - prices[i - 1], 0)
return result
动态规划
class Solution:
def maxProfit(self, prices: List[int]) -> int:
dp = [ [0, 0] for _ in range(len(prices))]
# max money in hand at ith day with a stock in hand
dp[0][0] = - prices[0]
# max profit at ith day
dp[0][1] = 0
for i in range(1, len(prices)):
# with a stock in hand and not buying stock, or without a stock in hand and buy a stock
dp[i][0] = max(dp[i-1][0], dp[i-1][1] - prices[i])
# without stock in hand, or with a stock in hand and selling a stock
dp[i][1] = max(dp[i-1][1], dp[i-1][0] + prices[i])
return dp[-1][1]
55. 跳跃游戏
贪心
- 其实跳几步无所谓,关键在于可跳的覆盖范围!
- 不一定非要明确一次究竟跳几步,每次取最大的跳跃步数,这个就是可以跳跃的覆盖范围。这个范围内,别管是怎么跳的,反正一定可以跳过来。
- 那么这个问题就转化为跳跃覆盖范围究竟可不可以覆盖到终点!
- 每次移动取最大跳跃步数(得到最大的覆盖范围),每移动一个单位,就更新最大覆盖范围。
- 贪心算法局部最优解:每次取最大跳跃步数(取最大覆盖范围),整体最优解:最后得到整体最大覆盖范围,看是否能到终点。
- i每次移动只能在cover的范围内移动,每移动一个元素,cover得到该元素数值(新的覆盖范围)的补充,让i继续移动下去。
class Solution:
def canJump(self, nums: List[int]) -> bool:
max_cover = 0
i = 0
while i <= max_cover:
max_cover = max(max_cover, i + nums[i])
if max_cover >= len(nums) - 1:
return True
i += 1
return False
45. 跳跃游戏 II
贪心1
- 本题要计算最小步数,那么就要想清楚什么时候步数才一定要加一呢?
- 贪心的思路,局部最优:当前可移动距离尽可能多走,如果还没到终点,步数再加一。整体最优:一步尽可能多走,从而达到最小步数。
- 思路虽然是这样,但在写代码的时候还不能真的就能跳多远跳远,那样就不知道下一步最远能跳到哪里了。
- 所以真正解题的时候,要从覆盖范围出发,不管怎么跳,覆盖范围内一定是可以跳到的,以最小的步数增加覆盖范围,覆盖范围一旦覆盖了终点,得到的就是最小步数!
- 这里需要统计两个覆盖范围,当前这一步的最大覆盖和下一步最大覆盖。如果移动下标达到了当前这一步的最大覆盖最远距离了,还没有到终点的话,那么就必须再走一步来增加覆盖范围,直到覆盖范围覆盖了终点。
class Solution:
def jump(self, nums: List[int]) -> int:
cur_max, next_max = 0, 0
min_step = 0
i = 0
for i in range(len(nums)):
# i is in the range of current cover and what is the max next cover for the i in current cover?
next_max = max(nums[i] + i, next_max)
# choose to jump max step in each cover interval
if i == cur_max:
if cur_max != len(nums) - 1:
min_step += 1
cur_max = next_max
if next_max >= len(nums) - 1:
break
else:
break
return min_step
贪心2
针对于方法一的特殊情况,可以统一处理,即:移动下标只要遇到当前覆盖最远距离的下标,直接步数加一,不考虑是不是终点的情况。
想要达到这样的效果,只要让移动下标,最大只能移动到nums.size - 2的地方就可以了。
因为当移动下标指向nums.size - 2时:
- 如果移动下标等于当前覆盖最大距离下标, 需要再走一步(即ans++),因为最后一步一定是可以到的终点。(题目假设总是可以到达数组的最后一个位置
- 如果移动下标不等于当前覆盖最大距离下标,说明当前覆盖最远距离就可以直接达到终点了,不需要再走一步
class Solution:
def jump(self, nums: List[int]) -> int:
cur_max, next_max = 0, 0
min_step = 0
i = 0
for i in range(len(nums) - 1):
next_max = max(nums[i] + i, next_max)
if i == cur_max:
min_step += 1
cur_max = next_max
return min_step