標籤:買入賣出問題
Say you have an array for which the ith element is the price of a given stock on day i.Design an algorithm to find the maximum profit. You may complete at most two transactions.Note:You may not 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.
題意:股票的買入賣出。你只有兩次機會買入賣出。
public class Solution { public int maxProfit(int[] prices) { if(prices==null || prices.length<2)return 0; //O(n^2)哎 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]從左往右遍曆,表示到第i天時賣出能賺到的最大錢 // int[] first=new int[prices.length]; // //second[i]從右往左遍曆,表示從第i天到最後一天能賺到的最大錢。本質還是分兩部分計算。只不過是分開兩次掃描數組 // 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:解法一是直接以第i天為界,求兩邊的最大收益。但是需要O(N^2)。
最佳化:用倆數組,遍曆兩次。
Leetcode 123. Best Time to Buy and Sell Stock III JAVA語言