LeetCode筆記:121. Best Time to Buy and Sell Stock

問題:

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.

大意:

說你有一個由每天的股票價格組成的數組。
如果你只能進行一次交易(比如購買或者銷售一個股票),設計一個算法來獲取最大利潤。
例子1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
最大的利潤為:6-1 = 5(不是7-1 = 6,因為銷售價格需要比購買價格大)
例子2:
Input: [7, 6, 4, 3, 1]
Output: 0
這個例子中,無法進行交易,所以最大收益為0。

思路:

這道題的意思就是,數組里的數按照順序是每天的股票價格,你可以選擇在某一天購買,然后再之后的某一天銷售掉,銷售的日子當然必須在購買的日子之后,也就是數組的順序要靠后一些。要計算在哪兩天進行買賣收益最大。這道題乍一看需要n*n的循環去計算每出一個價格后的最優解,我也是這樣一開始就這樣做,但是這樣做時間復雜度太高,會超時,實際上也不用這么復雜。我們只需要每出一個新價格后,先判斷這個價格減去我之前選擇的買進價格后是否比之前的收益要大,以及這個新價格是否比我之前的買入價格要低,然后進行相應的操作即可,如果收益更大,就把這個收益記錄下來,如果比買入價格低,就把買入價格換成這個價格。不需要擔心這樣直接換了之后往后計算的收益會不會不如之前,因為我們已經記錄了在此之前的最大收益了,每次都會做對比的,而更換了更低的買入價格后,我們繼續往后看能不能獲得更大的收益,因為對于后面的數字來說這個數就是之前最小的買入價格了。其實想清楚后要進行的操作很簡單,但如果想不清楚,就會覺得可能性太多了,要面面俱到總是會出問題,這里就要求頭腦清晰了。

代碼(Java):

public class Solution {
    public int maxProfit(int[] prices) {
        int result = 0;
        int small = 0;
        if (prices.length == 0) return 0;
        else small = prices[0];
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] - small > result) result = prices[i] - small;
            if (prices[i] < small) small = prices[i];
        }
        return result;
    }
}

代碼(C++)

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int buy = prices[0];
        int profit = 0;
        for (int i = 0; i < prices.size(); i++) {
            if (prices[i] < buy) {
                buy = prices[i];
            }
            int temp = prices[i] - buy;
            if (temp > profit) {
                profit = temp;
            }
        }
        return profit;
    }
};

合集:https://github.com/Cloudox/LeetCode-Record


查看作者首頁

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容