Skip to content

LeetCode: 121-Best Time to Buy and Sell Stock 解題紀錄

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.


Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.


Constraints:

  • 1 <= prices.length <= 105
  • 0 <= prices[i] <= 104

輸入會給我們一組整數陣列,從左到右分別是每天的股票價格。我們要做的便是讓程式決定怎麼樣買可以獲得最大的利潤(profit)。我們只能選擇一天買進、一天賣出。

如果無法獲得任何利潤,當然就是什麼也沒買,返回 0。


解題思路

解題的方法非常地單純:隨時紀錄當天價格,並比較是否比之前買入的價格低,若是有價格更低的天數,便隨時將買入的天數定為價格低的那天。

同時,每當遇到賣出價格高的日子,則隨時將賣出的利潤價格與歷史最高利潤價格做比較。

如此一來,等程式跑完後便能知道在哪天買入、哪天賣出的利潤最高。

這題題目是比較沒有實戰意味的。僅僅只是考好玩的感覺。


C++ 程式碼

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




References

Leave a Reply取消回覆

Exit mobile version