Problem
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Explanation
-
Note that the maximum transaction is 2, and we can sell and buy on the same day. We can divide this array into two parts:
prices[0:n-1] => prices[0:i] + prices[i:n-1]
, so we need to find the maximum of profit on or before dayi
, and the maximum profit on or after dayi
, then the result will be the sum of the two. -
We can solve this problem by calculating every indexes
i
’smostLeftProfit
andmostRightProfit
, then the result will be the maximum of the sum of these two. -
First, we use an array to store all indexes
mostLeftProfit
by iterating from beginning to the end. Then, we iterate from the end back to the beginning to calculate themostRightProfit
and compare each index’s mostLeftProfit and its mostRightProfit to get the final maximum result.
Solution
1 |
|