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. You are in most of the transactions.
Note:
Engage in multiple transactions on the same time (ie, you must sell the stock before you buy again).
Puzzle : reference http://www.cnblogs.com/springfor/p/3877068.html
According to the requirements of the title, up to two times to buy and sell stocks, and the hands can not have 2 stocks, is not two consecutive buy operations.
Therefore, two trades must be distributed within 2 intervals, that is, the action is: buy sell, buy sell.
Further, we can divide into 2 intervals [0,i] and [I,len-1],i can take 0~len-1.
Then the maximum profit for the two trades is: the maximum profit in two intervals and the maximum profits.
The maximum benefit of a division is: profit[i] = Maxprofit (interval [0,i]) + maxprofit (interval [i,len-1]);
The final maximum profit is: Maxprofit (profit[0], profit[1], profit[2], ..., profit[len-1]).
C + + Implementation code:
#include <iostream>#include<vector>using namespacestd;classSolution { Public: intMaxprofit (vector<int> &prices) { if(Prices.empty ())return 0; intn=prices.size (); inti; intlow=prices[0]; intLeft[n]; left[0]=0; for(i=1; i<n;i++) { low=min (low,prices[i-1]); Left[i]=max (left[i-1],prices[i]-Low ); } inthigh=prices[n-1]; intRight[n]; Right[n-1]=0; for(i=n-2; i>=0; i--) { high=max (high,prices[i+1]); Right[i]=max (right[i+1],high-Prices[i]); } intmaxsum=0; for(i=0; i<n;i++) {maxsum=max (maxsum,left[i]+Right[i]); } returnmaxsum; }};intMain () {solution S; Vector<int> vec={1,4,6,8,3,5,9,3,6}; cout<<s.maxprofit (VEC) <<Endl;}
best time to Buy and Sell Stock III