↓快轉到主要內容
  1. LeetCode/

LeetCode 122: Best Time To Buy And Sell Stock II

·2 分鐘· ·
LeetCode Medium Dynamic-Programming Greedy State-Machine
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: medium 第一次嘗試:2026-05-17 來源:Day 22 learning note

學習脈絡
#

這篇是從 learning note 裡該 LeetCode 題目的段落重新整理出來的版本。我保留當天筆記中的修正點、比較點、容易犯錯的地方,並移除同一天其他非 LeetCode 主題,避免文章內容混題。

當天筆記摘錄
#

Problem 2 - LC 122 Best Time To Buy And Sell Stock II
#

  • Pattern: unlimited-transactions state machine.

Why This Fits
#

This is the simplest full stock-state problem:

  • hold = best profit while holding a stock after day i
  • cash = best profit while not holding a stock after day i

Because transactions are unlimited, the key difference from Stock I is:

after selling, you are allowed to re-enter later

Core Transitions
#

hold = max(previous_hold, previous_cash - price)
cash = max(previous_cash, previous_hold + price)

Interview-Ready Explanation
#

I define hold as the best profit if I end the day holding one stock, and cash as the best profit if I end the day not holding stock. On each day, I either keep the previous state or transition by buying or selling once. The value of the problem is not the formula itself, but that each transition comes directly from the meaning of the state.

Common Mistakes
#

  • updating states in the wrong order without preserving previous values
  • treating this as arbitrary greedy accumulation without understanding state meaning
  • not being able to explain why buy/sell transitions are legal

正確解法
#

上面的筆記保留了推理脈絡和當天需要修正的點。下面是我會提交的版本。

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

複雜度
#

Time O(n), Space O(1).

要特別避免的錯誤
#

  • Overcomplicating with buy/sell dates.
  • Forgetting unlimited transactions means adjacent rises can be combined.

面試口說整理
#

先講清楚 state definition,再說 transition 為什麼維持這個 state。只要這題有 loop direction、狀態壓縮、或題型相似但 answer shape 不同的地方,就要主動講出來,因為那通常就是這類題最容易出錯的點。

相關文章

LeetCode 309: Best Time to Buy and Sell Stock with Cooldown
·2 分鐘
LeetCode Medium Dynamic-Programming State-Machine
LeetCode 309 解題筆記,依照原始 learning note 重新整理
LeetCode 714: Best Time to Buy and Sell Stock with Transaction Fee
·2 分鐘
LeetCode Medium Dynamic-Programming State-Machine
LeetCode 714 解題筆記,依照原始 learning note 重新整理
LeetCode 3638: Maximum Balanced Shipments
·1 分鐘
LeetCode Medium Dynamic-Programming Greedy Monotonic-Stack Array
LeetCode 3638 解題筆記:貪心,一段一旦出現比這段最大值小的數就馬上切;因為切之前的那段是非遞減的,最大值就是前一個數
LeetCode 397: Integer Replacement
·1 分鐘
LeetCode Medium Dynamic-Programming Greedy Bit-Manipulation Memoization
LeetCode 397 解題筆記:偶數一定除以 2;奇數選 +1 或 -1,用記憶化遞迴;n 很大不能開 n 大小的陣列
LeetCode 435: Non-overlapping Intervals
·1 分鐘
LeetCode Medium Array Dynamic-Programming Greedy Sorting
LeetCode 435 解題筆記:最少刪幾個 = 總數減掉最多能保留幾個;按右端點排序,貪心保留結束最早的
LeetCode 2745: Construct the Longest New String
·1 分鐘
LeetCode Medium Dynamic-Programming Math Greedy Brainteaser
LeetCode 2745 解題筆記:AA 和 BB 必須交替出現,最多用 min(x, y) 對,多的那種還能再多放一個;AB 全部都能接上