本文完整拆解 LeetCode 122 Best Time to Buy and Sell Stock II 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Best Time to Buy and Sell Stock II 一次弄懂。
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 integer array prices where prices[i] is the price of a given stock on the ith day.
On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
Find and return the maximum profit you can achieve.
Example 1:
Input: prices = [7,1,5,3,6,4] Output: 7 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7.
Example 2:
Input: prices = [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Total profit is 4.
Example 3:
Input: prices = [7,6,4,3,1] Output: 0 Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.
Constraints:
1 <= prices.length <= 3 * 1040 <= prices[i] <= 104
Python
# time complexity: O(n)
# space complexity: O(1)
from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
for i in range(1, len(prices)):
if prices[i] > prices[i-1]:
profit += prices[i] - prices[i-1]
return profit
prices = [7, 1, 5, 3, 6, 4]
print(Solution().maxProfit(prices))
Best Time to Buy and Sell Stock II 解題思路
可以無限次買賣,而且同一天可以先賣再買,這讓問題瞬間變簡單:任何一段上漲區間的總獲利,都等於這段區間內每一天漲幅的總和。所以只要把所有「今天比昨天貴」的差額全部加起來就是答案,完全不必判斷哪裡是波段起點或終點。
Best Time to Buy and Sell Stock II 演算法步驟
- 初始化 profit 為 0。
- 從第二天開始走訪陣列。
- 若 prices[i] 大於 prices[i-1],就把差額 prices[i] – prices[i-1] 累加到 profit。
- 走完所有天數後回傳 profit。
Best Time to Buy and Sell Stock II 複雜度分析
| 項目 | 複雜度 |
|---|---|
| 時間複雜度 | O(n) |
| 空間複雜度 | O(1) |
單次線性掃描,每一步只做一次比較與一次加法,時間 O(n)、空間 O(1)。這題是貪婪演算法最乾淨的範例之一:局部最優(每個上漲日都吃下)直接組成全域最優。
Best Time to Buy and Sell Stock II 的邊界情況與常見錯誤
- 價格全程下跌時回傳 0,不要累加負的差額。
- 陣列長度小於 2 時答案為 0。
- 不需要真的找出買賣日期,只要累加差值;若題目要求回報交易次數才需額外記錄。
- 這個貪婪解法只在「無交易次數上限且無手續費」的前提下成立。
Best Time to Buy and Sell Stock II 其他解法比較
| 解法 | 時間 | 空間 | 說明 |
|---|---|---|---|
| 動態規劃(持有/未持有兩狀態) | O(n) | O(1) | 可擴充到有手續費或冷凍期的變形 |
| 找出所有波段的谷與峰 | O(n) | O(1) | 結果相同但實作較囉嗦 |
| 貪婪累加正差額 | O(n) | O(1) | 本文採用,最精簡 |
