训练营day49|动态规划|121. 买卖股票的最佳时机、122.买卖股票的最佳时机II
121. 买卖股票的最佳时机
要点
- 贪心的思路很简单,就是每次更新最小左区间,然后对每个遍历的价格更新最大的result即可。
- 动态规划的思路比较绕,需要区分第i天是否持有股票来进行状态转移,理解这一点后状态转移公式很好写。且最终结果是第i天不持有股票的结果
代码
class Solution:
def maxProfit(self, prices: List[int]) -> int:
dp = [[0] * 2 for _ in range(len(prices))]
dp[0][0] = -prices[0] #第i天持有股票的最大现金
dp[0][1] = 0 # 第i天不持有股票的最大现金
for i in range(1, len(prices)):
dp[i][0] = max(dp[i - 1][0], -prices[i])
dp[i][1] = max(dp[i - 1][1], dp[i -1][0] + prices[i])
return dp[-1][1]
122.买卖股票的最佳时机II
要点
- 这道题贪心的思路是把所有后一天价格大于前一天价格的差值累加起来
- 动态规划的思路是每天所能获取的最大利润等于前一天的最大利润+max(今天的价格-昨天的价格,0)
代码
class Solution:
def maxProfit(self, prices: List[int]) -> int:
dp = [0] * len(prices)
for i in range(1, len(prices)):
dp[i] = dp[i - 1] + max(0, prices[i] - prices[i - 1])
return dp[-1]