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).
Analysis
One dimensional dynamic planning.the max profit at day i is the max profit before day i + max profit after day i.
Given an i, split the whole array into two parts:
[0,i] and [i+1, n], it generates two max value based on i, Max(0,i) and Max(i+1,n)
So, we can define the transformation function as:
Maxprofix = max(Max(0,i) + Max(i+1, n)) 0<=i<n
Java
public int maxProfit(int[] prices) { int maxPro = 0; if(prices.length>1){ ArrayList<Integer> mp = new ArrayList<>(); int minP = prices[0]; mp.add(maxPro); for(int i=1;i<prices.length;i++){ if(prices[i]-minP>=maxPro){ maxPro = prices[i]-minP; } if(minP>prices[i]) minP = prices[i]; mp.add(maxPro); } maxPro =0; int maxP = prices[prices.length-1]; for(int i=prices.length-2;i>=0;i--){ if(maxPro<maxP-prices[i]+mp.get(i)){ maxPro = maxP-prices[i]+mp.get(i); } if(prices[i]>maxP) maxP = prices[i]; } } return maxPro; }
c++
int maxProfit(vector<int> &prices){ if(prices.size()<=1) return 0; if(prices.size()==2) return prices[1]>prices[0]?prices[1]-prices[0]:0; vector<int> maxFromLeft(prices.size(),0); vector<int> maxFromRight(prices.size(),0); int minL = INT_MAX, max=INT_MIN, diff; for(int i=0;i<prices.size();i++){ if(prices[i]<minL) minL = prices[i]; diff = prices[i]- minL; if(diff >max) max = diff; maxFromLeft[i] = max; } int maxR = INT_MIN; max = INT_MIN; for(int i=prices.size()-1;i>=0;i--){ if(prices[i]>maxR) maxR = prices[i]; diff = maxR - prices[i]; if(diff > max) max = diff; maxFromRight[i] = max; } max = INT_MIN; for(int i=0;i<prices.size()-1;i++){ int diff = maxFromLeft[i]+maxFromRight[i+1]; if(diff > max) max = diff; } if(max < maxFromRight[0]) max = maxFromRight[0]; return max; }