Topic:
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).
Ideas:
1. The transaction is similar to the practice of trading once, simply split the array into two arrays, and then calculate the maximum value of two array transactions once, then add;
2. Assuming that the array is split at index i, place the maximum value of the array element between 0-i into List1, and place the maximum value of the array element between the i-n into List2
3. Traverse I to determine the value of I, to obtain the maximum benefit
V1 version
public class Solution {public int maxprofit (int[] prices) {if (prices==null| | Prices.length<=0) return 0; int len=prices.length; Array length list<integer> dp_pre=new arraylist<integer> (); 0-i Sub-array list<integer> dp_post=new arraylist<integer> (); I-n the word group int min_pre=integer.max_value; int max_pre=0; for (int i=0;i<len;i++) {if (prices[i]<min_pre) min_pre=prices[i]; if (prices[i]-min_pre>max_pre) Max_pre=prices[i]-min_pre; Dp_pre.add (Max_pre); }//Fill dp_pre int max_post=p RICES[LEN-1]; int max_pro=0; for (int i=len-1;i>=0;i--) {if (prices[i]>max_post) max_post=prices[i]; if (Max_post-prices[i]>max_pro) max_pro=max_post-pRices[i]; Dp2.add (Max_pro); }//fill dp_post int max=0; for (int i=1;i<len;i++) {if (Dp1.get (i) +dp2.get (len-1-i) >max) max=dp1.get (i) +dp2.get (len -1-I); } return max; }}
V2 version---the same idea, relatively concise
public class Solution {public int maxprofit (int[] prices) { if (len<=0) return 0; int maxpro1=0; int min1=prices[0]; List<integer> mp=new arraylist<integer> (); Mp.add (MaxPro1); for (int i=1;i<len;i++) { if (prices[i]-min1>maxpro1) maxpro1=prices[i]-min1; if (prices[i]<min1) min1=prices[i]; Mp.add (MaxPro1); } int maxpro2=0; int max2=prices[len-1]; for (int i=len-2;i>=0;i--) { if (max2-prices[i]+mp.get (i) >maxpro2) { Maxpro2=max2-prices[i]+mp.get ( i); } if (PRICES[I]>MAX2) max2=prices[i]; } return MaxPro2;} }
123-best time to Buy and Sell Stock III