Best Time to Buy and Sell Stock

Leetcode-Algorithm-DP-121

題目:
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.
(假定你有一個數組,數組中的每個元素表示元素所在索引的那天的價格。如果你只被允許最多完成一次交易,也就是進行一次買賣,請設計一個算法找到最大的收益。)

例子:
輸入:[7, 1, 5, 3, 6, 4].
輸出:5.
解釋:由於只能進行一次交易,因此在第一天買入和在第4天賣出能得到的收益最大,收益爲6-1=5。

輸入:[7, 6, 4, 3, 1].
輸出:0.
解釋:由於賣出日期必須大於買入日期,因此對於當前數組無論怎麼樣的買賣都不能得到正的收益,因此,最大收益爲0。


題解:
方法1:(暴力法)
做容易想的辦法就是把所有可能的買賣收益計算出來,然後找出其中的最大值。所謂“可能的買賣”也就是在賣出日期大於等於買入日期的前提下進行所有的一次買賣。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int max = 0;
        for (int i = 0; i < prices.size(); ++i)
            for (int j = i+1; j < prices.size(); ++j)
                max = (max > (prices[j]-prices[i]) ? max : prices[j]-prices[i]);

        return max;
    }
};

分析:
由於要計算出所有索引i和j間且i<=j的差值,因此總的時間複雜度爲O(n2) 。在leetcode上會導致超時。


方法2:(動態規劃DP)
雖然不清楚怎麼樣的買賣組合才能得到最大的收益,但是我們知道,在允許買賣的那天開始(也就是索引爲0,第0天)到之後的某一天(第i天),期間的最大收益有兩種可能:①到第i天的最大收益就是到第i-1天的收益,也就是說第i天的價格不影響前i-1天的最大收益;②當第i天的價格會影響前i-1天的最大收益時,也就是說在第i天賣出能夠得到更大的收益,這時最大收益就是第i天的價格減去前i-1天的最低價格。所以可以通過動態規劃解決這個問題。狀態轉移函數爲:f(i)=max{f(i-1), prices[i]-minPrice},其中f(i)表示到第i天爲止得到的最大收益,minPrice表示錢i-1天的最低價格。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if (prices.empty()) return 0;

        vector<int> profit;
        int maxPro = 0;
        int minPrice = prices[0];
        profit.push_back(0);

        for (int i = 1; i < prices.size(); ++i) {
            minPrice = min(prices[i], minPrice);
            profit.push_back(max(profit[i-1], prices[i] - minPrice));
            maxPro = max(maxPro, profit[i]);
        }

        return maxPro;
    }
};

分析:
由於算法的整個過程只需要遍歷一次prices容器,因此總的時間複雜度爲O(n)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章