1. 程式人生 > >[LeetCode] 121. Best Time to Buy and Sell Stock Java

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

most length 如果 時間復雜度 ase 最大差值 new [1] cas

題目:

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: 5

max. 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: 0

In 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