dp定义为dp[i][k][0]第i天没有持股,恰好完成了k笔交易(卖出时算一笔交易完成)的情况下可以获得的最大利润
dp[0][k>=1][0or1] 不合法,因为是第一天不可能进行过交易
注意按照这个通解,由于定义的是恰好完成k笔交易在卖出时算交易完成,根据递推公式无法涉dp[i][0][1]
所以这一步放在k的循环之外
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
#dp定义为dp[i][k][0]第i天没有持股,恰好完成了k笔交易(卖出时算一笔交易完成)的情况下可以获得的最大利润
#base case dp[0][0][0] = 0 dp[0][0][1] = -prices[0]
#dp[0][k>=1][0or1] 不合法,因为是第一天不可能进行过交易
n = len(prices)
k = min(k,n//2)
res = 0
dp = [[[0]*2 for j in range(k+1)] for i in range(n)]
dp[0][0][1] = - prices[0]
for j in range(1,k):
dp[0][j][0] = -0x3f3f3f3f
dp[0][j][1] = -0x3f3f3f3f
for i in range(1,n):
dp[i][0][1] = max(dp[i - 1][0][1], dp[i - 1][0][0] - prices[i]) #第i天进行了0次交易持有股票
for j in range(k,0,-1):
dp[i][j][0] = max(dp[i-1][j][0],dp[i-1][j-1][1] + prices[i])
dp[i][j][1] = max(dp[i-1][j][1],dp[i-1][j][0] - prices[i])
for i in range(1,k+1):
res = max(res,dp[n-1][i][0])
return res
持有和非持有分别用两个变量
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
#dp定义为dp[i][k][0]第i天没有持股,恰好完成了k笔交易(卖出时算一笔交易完成)的情况下可以获得的最大利润
#base case dp[0][0][0] = 0 dp[0][0][1] = -prices[0]
#dp[0][k>=1][0or1] 不合法,因为是第一天不可能进行过交易
if not prices:
return 0
n = len(prices)
k = min(k, n // 2)
buy = [[0] * (k + 1) for _ in range(n)]
sell = [[0] * (k + 1) for _ in range(n)]
buy[0][0], sell[0][0] = -prices[0], 0
for i in range(1, k + 1):
buy[0][i] = sell[0][i] = float("-inf")
for i in range(1, n):
buy[i][0] = max(buy[i - 1][0], sell[i - 1][0] - prices[i])
for j in range(1, k + 1):
buy[i][j] = max(buy[i - 1][j], sell[i - 1][j] - prices[i])
sell[i][j] = max(sell[i - 1][j], buy[i - 1][j - 1] + prices[i]);
return max(sell[n - 1])