const solve = (nums) => { let left = 0, right = nums.length - 1; while (left < right) { const sum = nums[left] + nums[right]; if (sum === target) return [left, right]; }}
Problem Walkthrough

NeetCode Best Time to Buy and Sell Stock — Complete Walkthrough

NeetCode's approach to Buy and Sell Stock (#121) and its variants has become the standard explanation. Here is the complete breakdown of all variants from I to IV using NeetCode's framework.

10 min read|

Buy and Sell Stock: all variants from NeetCode perspective

From greedy (#121) to state machine DP (#309) — the complete stock family

The Buy and Sell Stock Family on LeetCode

Buy and Sell Stock is the most-asked greedy and dynamic programming family on LeetCode. It appears in interviews at every major tech company, and NeetCode's best time to buy and sell stock explanations have become the go-to resource for understanding every variant.

The family spans at least four core problems: #121 (one transaction), #122 (unlimited transactions), #309 (cooldown), and #188 (at most K transactions). Each builds on the previous one, and NeetCode's framework treats them all as variations of the same underlying state machine.

If you master the pattern behind #121, the jump to #122 is small. From there, #309 adds one constraint (cooldown), and #188 generalizes everything. This article walks through each variant using NeetCode's approach so you can see the progression clearly.

Buy and Sell Stock I (#121) — One Transaction, Greedy

LeetCode #121 is the starting point: you are given an array of prices and can make exactly one buy and one sell. The goal is to maximize profit. NeetCode's buy sell stock explanation for this variant is pure greedy — no DP table needed.

The approach tracks the minimum price seen so far as you iterate through the array. At each day, compute the profit if you sold today (current price minus minimum so far) and update your answer. This runs in O(n) time and O(1) space.

The key insight from NeetCode's walkthrough is that you never need to look backward. Once you have the running minimum, every future day is a potential sell day. You are always comparing against the best possible buy price.

  • Track min_price as you scan left to right
  • At each index, profit = price[i] - min_price
  • Update max_profit = max(max_profit, profit)
  • Time: O(n), Space: O(1)
💡

Pro Tip

Buy/Sell Stock I is greedy, II is greedy, but III (cooldown) and IV (K transactions) are DP — recognizing which variant you're facing determines your entire approach.

Buy and Sell Stock II (#122) — Unlimited Transactions

LeetCode #122 removes the single-transaction constraint: you can buy and sell as many times as you want, but you must sell before buying again. The neetcode stock problem approach here is also greedy, but the logic shifts.

Instead of tracking a global minimum, you collect every upward move. If tomorrow's price is higher than today's, you add the difference to your profit. This is equivalent to buying at every local minimum and selling at every local peak.

The elegance of this approach is that you do not need to identify peaks and valleys explicitly. Summing all positive consecutive differences gives you the same result. NeetCode's explanation makes this intuitive: imagine you could time-travel and capture every single upswing.

  • For each consecutive pair, if price[i+1] > price[i], add the difference
  • This captures every upward movement in the price array
  • No need to track buy/sell states explicitly
  • Time: O(n), Space: O(1)

Buy and Sell Stock with Cooldown (#309) — State Machine DP

LeetCode #309 introduces a constraint that breaks the greedy approach: after you sell, you must wait one day before buying again. This is where buy sell stock approach comparison becomes interesting, because the problem transitions from greedy to dynamic programming.

NeetCode models this as a state machine with three states: hold (you own a stock), sold (you just sold today), and rest (you are in cooldown or idle). Each day, you transition between states based on your action: buy, sell, or do nothing.

The recurrence relations are: hold[i] = max(hold[i-1], rest[i-1] - price[i]), sold[i] = hold[i-1] + price[i], rest[i] = max(rest[i-1], sold[i-1]). You only need the previous day's values, so this runs in O(n) time and O(1) space after optimization.

This state machine framework is the heart of NeetCode's approach to the entire stock family. Once you see the three states and their transitions, every variant becomes a matter of adjusting which transitions are allowed.

  1. 1Define three states: hold, sold, rest
  2. 2hold = max(previous hold, previous rest - price) — either keep holding or buy from rest
  3. 3sold = previous hold + price — sell what you are holding
  4. 4rest = max(previous rest, previous sold) — either stay resting or transition from sold
  5. 5Answer is max(sold[n-1], rest[n-1]) — you never want to end holding
ℹ️

Key Insight

All Buy/Sell Stock variants can be unified as state machine problems — at any day you're in one of 3 states: holding, not-holding, or cooldown. The variant determines which transitions are allowed.

Buy and Sell Stock IV (#188) — At Most K Transactions

LeetCode #188 is the generalized version: you can make at most K buy-sell transactions. This is the neetcode 121 walkthrough extended to its logical conclusion. When K is large enough (K >= n/2), it reduces to the unlimited case (#122). Otherwise, you need 2D DP.

The DP table is dp[k][day] where dp[k][day] represents the maximum profit using at most k transactions up to that day. For each transaction count and each day, you decide whether to complete a transaction today or carry forward the previous best.

NeetCode optimizes this by tracking a running maximum of dp[k-1][j] - price[j] as you scan, which avoids the inner loop and brings the complexity from O(n^2 * K) down to O(n * K). The space can also be optimized to O(n) by processing transactions in reverse.

  • dp[k][i] = max(dp[k][i-1], price[i] + max(dp[k-1][j] - price[j]) for j < i)
  • Optimize inner max with a running variable to avoid O(n^2)
  • When K >= n/2, fall back to the unlimited greedy solution
  • Time: O(n * K), Space: O(n * K) or O(n) optimized

The Pattern Across All Buy and Sell Stock Variants

All buy and sell stock variants are state machine problems at their core. At any given day, you are in one of a few states: holding stock, not holding stock, or in a cooldown period. The variant determines which transitions between states are allowed and how many times you can cycle through them.

For #121, the state machine has two states (holding, not holding) with exactly one cycle allowed. For #122, the same two states but unlimited cycles. For #309, a third state (cooldown) is added. For #188, the two-state machine is replicated K times.

NeetCode's framework unifies all of these by teaching you to think in states and transitions first, then derive the recurrence. This buy sell stock all variants perspective means you never memorize four separate solutions — you learn one framework and adjust the constraints.

Once you internalize this state machine model, you can handle any new stock variant that appears in interviews, including less common ones like #714 (with transaction fee) which simply modifies the sell transition by subtracting a fee.

Which Buy and Sell Stock Variants to Study for Interviews

Not all variants are equally important for interviews. LeetCode #121 and #122 cover roughly 90 percent of real interview appearances for this problem family. They test greedy thinking, array traversal, and the ability to optimize a brute-force approach.

#309 (cooldown) is excellent for practicing state machine DP and appears occasionally in interviews at companies that like DP questions. #188 (K transactions) is worth understanding for completeness, but it rarely appears outside of competitive programming or very senior-level interviews.

The best study order is #121 first (greedy baseline), then #122 (greedy extension), then #309 (state machine introduction), and finally #188 (generalized DP). Review each variant with YeetCode flashcards to lock in the state transitions and recurrence relations before your interview.

  • #121 — Must know. Greedy, O(n). Appears constantly in interviews.
  • #122 — Must know. Greedy extension. Quick follow-up in interviews.
  • #309 — Good to know. State machine DP. Great for DP practice.
  • #188 — Nice to know. Generalized 2D DP. Rarely asked directly.
  • #714 — Bonus. Transaction fee variant. Minor tweak to #122.
⚠️

Interview Priority

Don't study all 6+ Buy/Sell Stock variants for interviews — #121 (one transaction) and #122 (unlimited) cover 90% of interview appearances. The others are for DP practice, not interview priority.

Ready to master algorithm patterns?

YeetCode flashcards help you build pattern recognition through active recall and spaced repetition.

Start practicing now