Problem
Say you have an array for which the i-th element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most k transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Example 1:
1 |
|
Example 2:
1 |
|
Explanation
-
We can use dynamic programming to solve this problem.
-
Dynamic state is a two dimensional array
dp[t][d]
, row is transaction and column is the day, and it represents the maximum profit can be made using at mostt
transaction ind
day. Note, the length of the row ist+1
because we need consider zero transaction. -
Dynamic init is
dp[0][d]
(top row) all values will be zero because we are not making any transaction.dp[t][0]
all (left column) will be zero because if only has one day, then we can’t make any profit for one day. -
Dynamic function will be taking the maximum profit of either not making any transaction on day
d
, which isdp[t][d-1]
; another way is make transaction on dayd
, which the profit will beprices[d] - prices[m] + dp[t-1][m]
, wherem
will be the day we buy the stock and sell this stock on dayd
for the last transaction andm
will be from 0 to d-1. How do we find them
? We can switch the order ofprices[d] - prices[m] + dp[t-1][m]
toprices[d] + (dp[t-1][m] - prices[m])
, so we need to find them
that makse the maximum ofdp[t-1][m] - prices[m]
, let’s call thismaxDiff
. So, we can iterate them
from 0 to d-1, and find the maximum ofmaxDiff
. Therefore, the dynamic function ismax(dp[t][d-1], prices[d] + maxDiff
wheremaxDiff = dp[t-1][m]-prices[m]
form = 0 to d-1
. -
Dynamic result will be the bottom right value, which is
dp[t][d]
.
Solution
1 |
|