⚡Flashcard Drill➔
NeetCode #108LC-122MediumArrays & HashingNC 250
← Back to All Problems

#108 · #122 · Best Time to Buy and Sell Stock II(买卖股票的最佳时机 II)

📌 Problem Statement & Constraints

You are given an array prices where prices[i] is the price of a stock on day i. You may complete as many transactions as you like (buy one and sell one share multiple times), but you may not hold more than one share at a time. Return the maximum profit. Constraints: 1 <= prices.length <= 3 * 10^4, 0 <= prices[i] <= 10^4.

💡 Core Algorithmic Approaches

  1. With unlimited transactions and no cooldown or fee, the optimal strategy decomposes completely: capture every upward move.
  2. Think of the price curve. Any profitable multi-day hold can be split into the sum of its consecutive daily gains, so holding across a dip only loses money.
  3. Therefore the answer is simply the sum of max(0, prices[i] - prices[i-1]) over all days.
  4. A DP formulation also works (hold and cash states) and generalises to the constrained variants, but it is unnecessary here.

💻 Benchmark Python3 Implementation

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]   # capture every rise
        return profit


# DP formulation: generalises to cooldown / fee / k-transaction variants
class Solution2:
    def maxProfit(self, prices: List[int]) -> int:
        cash = 0                 # max profit with no share held
        hold = -prices[0]        # max profit while holding one share
        for p in prices[1:]:
            cash = max(cash, hold + p)   # sell today
            hold = max(hold, cash - p)   # buy today
        return cash

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): a single pass. The greedy version does one comparison per day; the DP version does two.
💾 Space Complexity
O(1): the greedy version needs one accumulator, the DP version two state variables.

⚠️ Interview Pitfalls & Follow-ups

  • Over-engineering with DP: it is correct but the greedy insight is the expected answer. Mention DP only as the generalisation path.
  • Trying to find local minima and maxima explicitly: it works but requires lookahead and edge handling; summing positive deltas is equivalent and simpler.
  • Confusing this with the single-transaction version (121): there the answer is the best single rise, which requires tracking the running minimum.
  • Subtracting negative deltas: only positive daily changes are captured; a falling day contributes 0.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

买卖股票的最佳时机 II

给你一个整数数组 prices,其中 prices[i] 表示某支股票第 i 天的价格。在每一天,你可以决定是否购买和/或出售股票。你在任何时候最多只能持有一股股票,但可以在同一天先买入再卖出。返回你能获得的最大利润。约束:1 ≤ prices.length ≤ 3 × 10^4;0 ≤ prices[i] ≤ 10^4。

核心要点

  • 关键洞察 :当交易次数不受限制时,只要相邻两天价格上涨(prices[i] &gt; prices[i-1]),就应该把这段利润全部吃掉。
  • 贪心策略 :遍历数组,把所有 max(0, prices[i] - prices[i-1]) 累加起来即为答案。
  • 为什么贪心正确 :一次跨多天的上涨(如 1 → 3 → 5)与「分两天各做一次交易」(1 买 3 卖,3 买 5 卖)的总收益完全相同,即 (3-1) + (5-3) = 5-1 。因此把任意一段上涨拆成若干相邻的小上涨不会损失收益。
  • 与 121 的对比 :121 限制只能交易一次,必须用「维护历史最低价」的 DP;122 允许无限次交易,贪心即可。两者的区别是本题的核心考点。

常见陷阱

  • 误用 121 的「历史最低价」思路 :121 的解法只能算一次交易的最大利润,用在本题会严重低估(例如 [1,2,3,4,5] 应得 4,而 121 的写法也能得到 4,但 [1,5,1,5] 应得 8,121 的写法只得 4)。
  • 以为「同一天买卖」被禁止 :题目明确允许在同一天先买入再卖出,这正是把连续上涨拆成多笔交易能成立的前提。
  • 误以为需要「找所有波谷与波峰」 :虽然用波谷波峰也能做对,但实现复杂易错;相邻差累加是等价且更简洁的写法。
  • 被追问 含手续费(714)或含冷冻期(309) 时答不上来:一旦加入手续费,拆分成多笔就不再等价(每笔都要付手续费),此时必须用状态机 DP。

参考实现

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