def maxProfit(k: int, prices: List[int]) -> int:
if k==0 or len(prices) <= 1:
return(0)
dp = [[0 for _ in range(len(prices))] for _ in range(k+1)]
for i in range(1, k+1):
for j in range(1, len(prices)):
profit = prices[j] - prices[j-1] # profit vs yesterday
# once a transaction i is open we need to keep it until the end
# best profit for i transactions at day j is max between
# 1) best profit for i transactions at day j-1 + today profit (position i is already open)
# 2) best profit for i-1 transactions at day j-1 + today profit (position i has been open yesterday)
# 3) best profit for i-1 transactions at day j-1 (position i is still close)
# best profit for i transactions at day j-1 (dp[i][j-1]) is not in the max otherwise it would allow to open and close multiple positions
dp[i][j] = max(dp[i][j-1] + profit, dp[i-1][j-1] + profit, dp[i-1][j-1])
# at the end we take the best profit for today as the max between best profit between today and yesterday. It reprensents if it is best to close position yesterday or keep it until today. Once again this should be done outside the first loop otherwise it would allow to close and reopen multiple position
for j in range(1, len(prices)):
dp[i][j] = max(dp[i][j], dp[i][j-1])
return(dp[-1][-1])