LeetCode學習篇十六——Best Time to Buy and Sell Stock

題目:Say you have an array for which the i^th 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.

這道題比較簡單,因爲只考慮買一次和賣一次,沒有其他限制條件,所以直接對數組遍歷,用變量min_price存儲最低價格,然後動態更新max. difference。代碼實現如下,時間複雜度:O(n)

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