Leetcode 123. Best Time to Buy and Sell Stock III JAVA語言

來源:互聯網
上載者:User

標籤:買入賣出問題

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語言

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.