Say you has 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. Transactions. (Stock trading , up to two times)
Note:
Engage in multiple transactions on the same time (ie, you must sell the stock before you buy again).
Class Solution {public: int maxprofit (vector<int> &prices) { if (prices.size () ==0) return 0; int n=prices.size (); Vector<int> left (n); Vector<int> right (n); int min=prices[0]; int max=prices[n-1]; int res=0; for (int i=1;i<n;i++) { min=min<prices[i]?min:prices[i]; Left[i]=left[i-1]> (prices[i]-min) left[i-1]:(prices[i]-min); } for (int j=n-2;j>=0;j--) { max=max>prices[j]?max:prices[j]; Right[j]=right[j+1]> (Max-prices[j]) right[j+1]:(max-prices[j]); } for (int i=0;i<n;i++) { res=res> (Left[i]+right[i]) Res: (Left[i]+right[i]); } return res; }};
Up to two stock trades-best time to Buy and Sell stock III