Say you had an array for which the ith element was the price of a given stock on day i.design an algorithm to find the max Imum profit. You are in most of the transactions. Note:you engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). Subscribe to see which companies asked this question.
Test instructions: Buy and sell stocks. You only have two chances to buy and sell.
Public class solution { public int maxprofit (int[] prices ) { if (prices==null | | &NBSP;PRICES.LENGTH<2) return 0; //o (n^2) Hey int sum=0; for (int i=1;i<prices.length;i++) { int temp=getmax (prices,0,i) +getmax (prices,i+1,prices.length-1); if (temp>sum) sum=temp; } return sum; } Public static int getmax (int[] prices,int left,int right) { if (left>=prices.length) return 0; int min=prices[left]; int sum=0; for (int i=left+1;i <=right;i++) { min=math.min (Min, Prices[i]); sum=math.max (sum,prices[i]- Min); } System.out.println (sum); return sum; // } // //first[i] From left to right, indicating to the first day to sell the maximum money can be earned // int[] first=new int[prices.length]; // //second[i] is traversed from right to left, Represents the maximum money that can be earned from day I to the last day. The essence is still divided into two parts calculation. It's just a separate two-scan array // int[] second=new int[prices.length]; // Int min=prices[0]; // for (int i=1;i<prices.length;i++) { // min=math.min (Min,prices[i]); // first[i]=math.max (first[i-1],prices[i]-min); // } // // for (int i=0;i<prices.length;i++) { // // system.out.println (First[i]); // // } // int max=prices[prices.length-1]; // for (int i= prices.length-2;i>=0;i--) { // max=math.max (max,prices[i ]); // second[i]=math.max (Second[i+1],max-prices[i]); // } // int ret=0; // for (int i=0;i<prices. length;i++) { // //system.out.println (second[i]); // ret=math.max (First[i]+second[i],ret); // } // return ret;}}
PS: Solution One is directly to the first day of the boundary, to seek the maximum benefit on both sides. However, O (n^2) is required.
Optimization: Use two arrays, traverse two times.
Leetcode 123. best time to Buy and Sell Stock III Java language