1、题目描述(k = +infinity with cooldown)
https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
基础题:122. 买卖股票的最佳时机 II (贪心)(买卖任意多次,但任意时刻最多持有一股,k = +infinity)https://blog.csdn.net/IOT_victor/article/details/105742167
给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):
你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。
输入: [1,2,3,0,2]
输出: 3
对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]
(2 - 1) + (2 - 0)
2、代码详解
class Solution:
def maxProfit(self, prices):
if not prices:
return 0
n = len(prices)
dp_i_0 = 0
dp_i_1 = float('-inf') # 也可以赋值为-prices[0]
dp_pre_0 = 0 # !!代表 dp[i-2][0]
for i in range(n):
t = dp_i_0 # !!
# dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i])
dp_i_0 = max(dp_i_0, dp_i_1 + prices[i])
# dp[i][1] = max(dp[i-1][1], dp[i-2][0] - prices[i])
dp_i_1 = max(dp_i_1, dp_pre_0 - prices[i]) # !!第 i 天选择 buy 的时候,要从 i-2 的状态转移,而不是 i-1
dp_pre_0 = t # !!
return dp_i_0
# 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]
# (2-1) + (2-0)
prices = [1,2,3,0,2]
s = Solution()
print(s.maxProfit(prices)) # 3