[LeetCode] 121. Best Time to Buy and Sell Stock Java

來源:互聯網
上載者:User

標籤:比較   情況   example   new   價格   inpu   input   數組   ice   

 題目:

 Say you have an array for which the ith element is the price of a given stock on day i.

 If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

 Example 1:

Input: [7, 1, 5, 3, 6, 4]Output: 5max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

 Example 2:

Input: [7, 6, 4, 3, 1]Output: 0In this case, no transaction is done, i.e. max profit = 0.

題意及分析:給出一個股票的價格序列,買入一次賣出一次,求能獲得最大利潤。其實就是求一個數組中,後面的數減去前面的數能得到的最大值。最容易想到的肯定是每次選一個數,遍曆後面的數,求出直接的差然後和當前最大值進行比較,這樣時間複雜度為O(n*n),
但是最後會逾時。對題目進行分析,發現可以用動態規劃的方法求解。我們用一個數組res儲存到某點能有的最大值,首先對於其中一個數prices[i](1<i<length):
(1)如果當前的數大於前一個數,可以輕易得出到達該點可以得到的最大值res[i]為前一個數的最大值+(prices[i]-prices[i-1]),然後和當前最大值進行比較,大於當前最大值則重設最大值
(2)如果當前數小於前一個數,又分為兩種情況
  a.如果到前一個數的最大<=0,所以能到達當前點的最大差值res[i]為0
  b.如果到達前一個數最大差值大於0,則能到達當前點的最大差值res[i]為Math.max(res[i-1]+(prices[i]-prices[i-1]),0);
對一個數單獨處理最後遍曆剩下的數即可得到答案。

代碼:
public class Solution {    public int maxProfit(int[] prices) {        int length=prices.length;        int[] res=new int[length];        int max=0;        if(length<=1)        return 0;        res[0]=0;        res[1]=0;        for(int i=1;i<length;i++){        if(prices[i]>prices[i-1]){        res[i]=res[i-1]+(prices[i]-prices[i-1]);        if(max<res[i])        max=res[i];        }else{        if(res[i-1]<=0)        res[i]=0;        else{        res[i]=Math.max(res[i-1]+(prices[i]-prices[i-1]),0);        }        }        }        if(max>0) return max;        else return 0;    }}

 

  



[LeetCode] 121. Best Time to Buy and Sell Stock 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.