# 121. Best Time to Buy and Sell Stock ## 題目概要 給定一個陣列 prices,找出哪一天買入股票哪一天賣出能賺的利潤最多。如果無法獲取利潤就返回 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. ``` ## 解題技巧 - 買入必須在賣出之前。 - 從 index 0 開始慢慢判斷,設 prices[0] 為最小值,而 0 為最大值,並遍歷 prices ,用當前值減去最小值來記錄利潤,如果利潤比當前最大值還大就存下來,最後返回最大利潤。 ## 程式碼 ```javascript= var maxProfit = function(prices) { if (!prices.length) return 0; let min = prices[0]; let max = 0; for (let i of prices) { min = Math.min(min, i); const profit = i - min; max = Math.max(max, profit); } return max; }; ``` ![](https://i.imgur.com/PojwySy.png)