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.
Ideas:
1, the topic requests most trades two times, if only trades once, the question is "best time to Buy and Sell the Stock";
If the transaction must be traded two times, the first transaction is sold on the I trading day, then the problem degrades into the maximum benefit of 0 to I trading day and i+1 to the last trading day.
2. Therefore, from the 1th trading day, the maximum benefit of the first trading day is obtained, wherein 1<i<=a.length, the array maxleft;
From the last trade start, seek the maximum benefit from the first trading day to the last trading day, where 1<=i<a.length, get the array maxright;
3. Maximum benefit from Maxleft and Maxright
The code is as follows:
Public intMaxprofit (int[] prices) { if(Prices.length < 2) return0; int[] Maxleft =New int[Prices.length]; intLastin = 0;//indicates the lowest buy price in the first lastin days for(intI=1; i<prices.length;i++) { if(Maxleft[i-1] = = 0) { if(Prices[i] > Prices[i-1]) {Maxleft[i]= Prices[i]-prices[i-1]; Lastin= I-1; } } Else { if(Prices[i] >Prices[lastin]) { if(Prices[i]-prices[lastin] > Maxleft[i-1]) {Maxleft[i]= Prices[i]-Prices[lastin]; } Else{Maxleft[i]= Maxleft[i-1]; } } Else if(Prices[i] <Prices[lastin]) {Maxleft[i]= Maxleft[i-1]; Lastin=i; } Else{Maxleft[i]= Maxleft[i-1]; } } } int[] Maxright =New int[Prices.length]; intLastout =prices.length;//says the highest selling price is on the Lastout day for(intI=prices.length-2; i>=0; i--) { if(maxright[i+1] = = 0) { if(Prices[i] < prices[i+1]) {Maxright[i]= Prices[i+1]-Prices[i]; Lastout= I+1; } }Else { if(Prices[i] <Prices[lastout]) { if(Prices[lastout]-prices[i] > maxright[i+1]) {Maxright[i]= Prices[lastout]-Prices[i]; } Else{Maxright[i]= Maxright[i+1]; } } Else if(Prices[i] >Prices[lastout]) {Maxright[i]= Maxright[i+1]; Lastout=i; } Else{Maxright[i]= Maxright[i+1]; } } } intMax = 0; for(intI=1; i<prices.length-2; i++) { if(Maxleft[i] + maxright[i+1] >max) Max= Maxleft[i] + maxright[i+1]; } if(Max < maxleft[prices.length-1]) {max= Maxleft[prices.length-1]; } returnMax; }
LeetCode-123 best time to Buy and Sell Stock III