LeetCode 121 Best Time to Buy and Sell Stock I

1)題目:
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.
給定一個數組,每個元素分別代表每天的股票價格,要求只經過一次交易,即買入一次、賣出一次,求得獲取的最大利潤。注意:買入必須在賣出之前。
2)分析:
該題如果沒有時間複雜度要求,則很容易解出來。可以通過兩次遍歷數組,分別計算出數組中的每個數,即每一天如果作爲買入的那天,則獲取的最大利潤爲多少。然後在每天買入後可獲取的最大利潤列表中求最大的利潤。但是這種做法時間複雜度爲O(n2),空間複雜度爲O(n),還有很大的優化空間。
經過分析,該題目符合動態規劃的要求,即全部最優解的子問題也是局部最優解。例如假設一共有七天,七天時間可以獲取的最大利潤等於前六天可獲取的最大利潤第七天與前六天中的最小值的差值中取最大值。初始值爲第一天的利潤,爲0。
經過上述分析,時間複雜度可降到O(n).
code:

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices==null || prices.length<2){
            return 0;
        }
        int curMin=prices[0];
        int profit=0;
        int len=prices.length;
        for(int i=1;i<len;i++){
            if(curMin>prices[i]){
                curMin=prices[i];
            }
            profit=Math.max(profit,prices[i]-curMin);
        }
        return profit;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章