本文完整拆解 LeetCode 121 Best Time to Buy and Sell Stock 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Best Time to Buy and Sell Stock 一次弄懂。
Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link
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 <= 1050 <= prices[i] <= 104
Python
# time complexity: O(n)
# space complexity: O(1)
from typing import List
class Solution(object):
def maxProfit(self, prices: List[int]) -> int:
profit, smallestPrice = 0, 99999
for price in prices:
if price < smallestPrice:
smallestPrice = price
else:
profit = max(profit, price - smallestPrice)
return profit
PriceList = [7, 1, 5, 3, 6, 4]
solution = Solution()
print(solution.maxProfit(PriceList))
Best Time to Buy and Sell Stock 解題思路
只能買賣一次,代表答案一定是「某個賣出日的價格,減掉它之前出現過的最低價」。所以根本不需要兩層迴圈比對所有組合,只要一邊往右走、一邊記住到目前為止的歷史最低價,每天都用今天的價格減去它,取最大值即可。
Best Time to Buy and Sell Stock 演算法步驟
- 初始化 minPrice 為無限大、maxProfit 為 0。
- 由左到右走訪每一天的價格 price。
- 若 price 小於 minPrice,就更新 minPrice(代表找到更好的買點)。
- 否則計算 price – minPrice,若大於 maxProfit 就更新答案。
Best Time to Buy and Sell Stock 複雜度分析
| 項目 | 複雜度 |
|---|---|
| 時間複雜度 | O(n) |
| 空間複雜度 | O(1) |
只掃描陣列一次,每一步都是常數時間的比較與更新,因此時間為 O(n)。只用到兩個純量變數,空間是 O(1)。這是典型的「一次掃描 + 維護歷史極值」模式。
Best Time to Buy and Sell Stock 的邊界情況與常見錯誤
- 價格全程下跌時必須回傳 0,代表不交易,而不是回傳負數。
- 陣列長度 0 或 1 時沒有交易機會,答案是 0。
- 先更新 minPrice 再算利潤,或先算利潤再更新都可以,但不能在同一天同時買賣。
- 不要誤用「最大值減最小值」,因為最大值可能出現在最小值之前。
Best Time to Buy and Sell Stock 其他解法比較
| 解法 | 時間 | 空間 | 說明 |
|---|---|---|---|
| 雙層迴圈列舉所有買賣日 | O(n²) | O(1) | 最直覺,資料量大會超時 |
| 轉成最大子陣列和(Kadane) | O(n) | O(1) | 把價格差分後套用 Kadane,思路漂亮 |
| 一次掃描維護歷史最低價 | O(n) | O(1) | 本文採用,最直接好懂 |
