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).
Public classSolution { Public intMaxprofit (int[] prices) { /*each point in the entire interval is cut, then the maximum values of the left and right sub-intervals are computed, and then the maximum value of the entire interval is found using the O (n) time. It seems that after the encounter with 2 related issues, it is important to think about whether you can use the dichotomy to define two arrays left and right, array left[i] records the maximum profit of price[0..i], the array right[i] records price[i. N] the maximum profit. Finally, the time of O (n) is used to find Maxprofix = Max (Left (0,i) + right (i+1, N)) 0<=i<n*/ intlen=prices.length; if(len<=0)return0; intleft[]=New int[Len]; intright[]=New int[Len]; left[0]=0; intMinleft=prices[0]; for(inti=1;i<len;i++) {Left[i]=math.max (left[i-1],prices[i]-minleft); if(Minleft>prices[i]) minleft=Prices[i]; } Right[len-1]=0; intMaxright=prices[len-1]; for(intj=len-2;j>=0;j--) {Right[j]=math.max (right[j+1],maxright-Prices[j]); if(Maxright<prices[j]) maxright=Prices[j]; } intRes=0; for(inti=0;i<len;i++){ inttemp=right[i]+Left[i]; if(res<temp) res=temp; } returnRes; }}
[Leedcode 123] best time to Buy and Sell Stock III