Transferred from: http://www.cnblogs.com/ranranblog/p/5845010.html
The pigs can fly under the Tuyere. The bull market in China today is a "missed seven years". Give you an opportunity to review the history of a stock, known for a continuous n-day price movement, in the length of an integer array of n, the array of elements I (prices[i]) represents the stock price of the first day. Suppose you don't have a stock at first, but you have the opportunity to buy 1 shares and then sell 1 shares at most two times, and make sure you have no stock before you buy. If two trading opportunities are abandoned, the yield is 0. Design algorithms to calculate the maximum benefits you can get. Input value Range: 2<=n<=100,0<=prices[i]<=100
input Example:
3,8,5,1,7,8
Output example:
12
Law one: divided into two parts calculated separately
1 public Static intGetmax (int[] prices,intstart,intEnd)2 {3 intMax =0;4 intMin =prices[start];5 for(inti=start+1; i<=end;i++)6 {7 if(prices[i]-min>max)8max = prices[i]-min;9 if(prices[i]<Min)TenMin =prices[i]; one } a returnmax; - } - /** the * Calculate the maximum benefit you can get - * - * @param prices prices[i] that is, the stock price of the first day - * @return Integral type + */ - public Static intCalculatemax (int[] prices) + { a intsum =0; at - for(intI=1; i<prices.length;i++) - { - inttemp = Getmax (prices,0, I) +getmax (prices,i,prices.length-1); - if(temp>Sum) -sum =temp; in } - returnsum; to}
Law ii: using dynamic programming, left[i] identifies the maximum profit from the 0-i maximum profit right[i] from I to end
1 intCalculatemax (vector<int>prices) {2 intn=prices.size ();3 if(n<=1)4 return 0;5vector<int>left (n,0);6vector<int>right (n,0);7 intmin=prices[0];8 for(intI=1; i<n;i++)9 {Ten if(min>prices[i]) onemin=prices[i]; aLeft[i]=max (prices[i]-min,left[i-1]); - } - inthigh=prices[n-1]; the for(inti=n-2; i>=0; i--) - { - if(high<prices[i]) -High=prices[i]; +Right[i]=max (high-prices[i],right[i+1]); - } + intresult=0; a for(intI=0; i<n;i++) at { - if(right[i]+left[i]>Result) -result=right[i]+left[i]; - } - returnresult; -}
The pigs can fly under the Tuyere. The bull market in China today is a "missed seven years". Give you a chance to look back on the history of a stock that is known for a continuous n-day price movement, expressed as an array of integers of length n,