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 (ie, you must sell the stock before you buy again).
Solution: dp. max profit = max { l2r[0...i] + r2l[i+1...N-1] }. 0 <= i <= N-1
1 class Solution { 2 public: 3 // max_profit = max {l2r[0,1,...,i], r2l[i+1,...,N-1]} 4 int maxProfit(vector<int> &prices) { 5 if (prices.size() <= 1) { 6 return 0; 7 } 8 int N = prices.size(); 9 vector<int> l2r(N,0); 10 vector<int> r2l(N,0); 11 12 int minv = prices[0]; 13 for(int i = 1; i < N; i++) { 14 minv = min(minv, prices[i]); 15 l2r[i] = max(l2r[i-1], prices[i]-minv); 16 } 17 18 int maxv = prices[N-1]; 19 for(int i = N-2; i >= 0; i--) { 20 maxv = max(maxv, prices[i]); 21 r2l[i] = max(r2l[i+1], maxv-prices[i]); 22 } 23 24 int res = l2r[N-1]; 25 for(int i = 0; i < N-1; i++) { 26 res = max(res, l2r[i]+r2l[i+1]); 27 } 28 return res; 29 } 30 };