Skip to main content

188. Best Time to Buy and Sell Stock IV

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/

Python

Bottom Up DP

  • 3維的DP
from math import inf


class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
if not prices or not k:
return 0

dp = [
[
[-inf]*2 for _ in range(k+1)

] for _ in range(len(prices))
]

dp[0][0][0] = 0
dp[0][1][1] = -prices[0]

for i in range(1, len(prices)):
for j in range(k+1):
dp[i][j][0] = max(dp[i-1][j][0], dp[i-1][j][1]+prices[i])

if j > 0:
dp[i][j][1] = max(dp[i-1][j][1], dp[i-1][j-1][0]-prices[i])

return max(dp[len(prices)-1][j][0] for j in range(k+1))