dp
with dimensions [days][transactions][2]
to store the state of the maximum profit.dp[0][0][0]
to 0 and dp[0][1][1]
to -prices[0]
.i
from 1 to n-1
.i
, iterate over each transaction j
from 1 to k
.dp[i][j][1] = max(dp[i-1][j][1], dp[i-1][j-1][0] - prices[i])
.dp[i][j][0] = max(dp[i-1][j][0], dp[i-1][j][1] + prices[i])
.dp[n-1][j][0]
for all j
from 0 to k
.