# Leetcode 121. Best Time to Buy and Sell Stock ###### tags: `Leetcode(C++)` 題目 : https://leetcode.com/problems/best-time-to-buy-and-sell-stock/submissions/ 。 想法 : 買最低、賣最高。 紀錄之前買的最便宜股票,與現在搜尋的最貴股票價格相減。 如果有遇到更便宜的就更新最便宜股票。 時間複雜度 : O(n)。 程式碼 : ``` class Solution { public: int maxProfit(vector<int>& prices) { int l = prices.size(), prevp = INT_MAX, maxp = 0; for(int i=0 ; i<l ; i++){ if(prevp != INT_MAX) maxp = max(maxp , prices[i] - prevp); if(prevp > prices[i]){ prevp = prices[i]; } } return maxp; } }; ```