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
Publicstaticint Getmax (int[] Prices,intStart,intend) {intMax =0;intMin =Prices[start]; for(inti=start+1; i<=end;i++){if(prices[i]-min>max) Max= prices[i]-min;if(prices[i]<min) min=prices[i];}returnMax;}/** * calculate the maximum profit you can earn * * @param prices Prices[i] that is the stock price of the first day * @return integer type*/ Public Static intCalculatemax (int[] prices) { intsum =0; for(intI=1; i<prices.length;i++) { inttemp = Getmax (Prices,0, i) +getmax (prices,i,prices.length-1); if(temp>sum) sum=temp; } returnsum; }
Law II: Using dynamic programming, Left[i] identifies the maximum profit from the 0-i maximum profit Right[i] from I to end
intCalculatemax (vector<int>prices) { intn=prices.size (); if(n<=1) return 0; Vector<int>left (N,0); Vector<int>right (N,0); intmin=prices[0]; for(intI=1; i<n;i++) { if(min>prices[i]) min=Prices[i]; Left[i]=max (prices[i]-min,left[i-1]); } inthigh=prices[n-1]; 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; for(intI=0; i<n;i++) { 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,