15% off all plans & roadmaps Use code
See plansEditorial
Core insight
Best Time to Buy and Sell Stock II · Greedy Patterns
Core Insight for Best Time to Buy and Sell Stock II
The key intuition for solving LeetCode 122 efficiently lies in defining the "states" of our portfolio. On any given day i, we are in one of two conditions:
- Holding a stock: We bought a stock previously and haven't sold it yet.
- Not holding a stock: We have no active position (either we never bought, or we just sold).
We want to maximize our profit in both states for every day. The transition logic is:
- To be in the Not Holding state on day
i, we either:- Were not holding on day
i-1and did nothing. - Were holding on day
i-1and sold today atprices[i].
- Were not holding on day
- To be in the Holding state on day
i, we either:- Were holding on day
i-1and did nothing. - Were not holding on day
i-1and bought today atprices[i].
- Were holding on day
Visual Description:
Imagine a graph with two nodes representing the states: Cash (not holding) and Hold (holding). The time axis flows from left to right. At each time step t, arrows point from the states at t-1 to the states at t.
- The
Cashnode attreceives an input fromCashatt-1(weight 0) andHoldatt-1(weight+prices[t]). - The
Holdnode attreceives an input fromHoldatt-1(weight 0) andCashatt-1(weight-prices[t]). The algorithm simply traces the path that accumulates the highest value through this state graph.
Deep dive
Full breakdown
Full reasoning, pitfalls, and implementation flow
LeetCode 122: Best Time to Buy and Sell Stock II Solution & Explanation
Problem Overview
TL;DR: The optimal solution tracks two dynamic states—holding stock and not holding stock—updating the maximum profit for each state as we iterate through daily prices.
In the Best Time to Buy and Sell Stock II problem, you are provided with an array of daily stock prices. You may complete as many transactions (buy and sell) as you like, but you must sell your current holding before buying again. The goal is to determine the maximum profit achievable. This is a popular interview question that tests your ability to model state transitions or identify greedy properties in arrays.
Brute Force Approach for Best Time to Buy and Sell Stock II
The brute force approach attempts to simulate every possible sequence of buying and selling. Since we can make an indefinite number of transactions, this can be modeled as a recursion where, on each day, we have three choices depending on our state: buy (if not holding), sell (if holding), or do nothing.
Pseudo-code:
function calculate(prices, day, holding):
if day == length(prices):
return 0
// Option 1: Do nothing
profit = calculate(prices, day + 1, holding)
if holding:
// Option 2: Sell
sell_profit = prices[day] + calculate(prices, day + 1, false)
profit = max(profit, sell_profit)
else:
// Option 3: Buy
buy_profit = -prices[day] + calculate(prices, day + 1, true)
profit = max(profit, buy_profit)
return profitTime Complexity:
The decision tree branches exponentially. For an array of size , there are roughly possible sequences of decisions.
Why it fails:
The constraints allow prices.length up to . An exponential solution will immediately trigger a Time Limit Exceeded (TLE) error. We need a polynomial time solution, ideally linear .
Algorithm Strategy: Dynamic Programming (DP) Patterns
We utilize the "DP - Stock problems" subpattern to formalize the insight.
-
State Definition:
- Let
cashrepresent the maximum profit on dayiif we do not have a stock. - Let
holdrepresent the maximum profit on dayiif we do have a stock.
- Let
-
Initialization:
- On day 0 (before processing):
cash = 0(We start with 0 profit).hold = -prices[0](If we hold a stock on day 0, we must have bought it, costing us its price).
- On day 0 (before processing):
-
Recurrence Relation: For each price
pinprices:new_cash = max(cash, hold + p)- Logic: Either keep existing cash (do nothing) or sell the stock we are holding (realize profit).
new_hold = max(hold, cash - p)- Logic: Either keep holding existing stock (do nothing) or buy new stock using our current cash (reinvest).
-
Optimization: Since
day[i]only relies onday[i-1], we do not need a full DP table (array). We can use two integer variables, updating them in place.
Execution Flow
Let's trace the algorithm with prices = [7, 1, 5, 3, 6, 4].
-
Initialization:
cash = 0hold = -7(Bought at 7)
-
Day 2 (Price = 1):
new_cash = max(0, -7 + 1) = 0(Better to have not bought at 7)new_hold = max(-7, 0 - 1) = -1(Better to buy now at 1 than to have bought at 7)- Update:
cash = 0,hold = -1
-
Day 3 (Price = 5):
new_cash = max(0, -1 + 5) = 4(Sell at 5! Profit is 4)new_hold = max(-1, 0 - 5) = -1(Keep holding is better than buying fresh at 5)- Update:
cash = 4,hold = -1
-
Day 4 (Price = 3):
new_cash = max(4, -1 + 3) = 4(Don't sell, holding from day 2 yields less profit if sold now)new_hold = max(-1, 4 - 3) = 1(Buy at 3 using the 4 profit? Net state value is 1. This is better than the old hold state of -1)- Update:
cash = 4,hold = 1
-
Day 5 (Price = 6):
new_cash = max(4, 1 + 6) = 7(Sell at 6. Previous profit 4 + (6-3) = 7)new_hold = max(1, 4 - 6) = 1- Update:
cash = 7,hold = 1
-
Day 6 (Price = 4):
new_cash = max(7, 1 + 4) = 7new_hold = max(1, 7 - 4) = 3- Update:
cash = 7,hold = 3
-
Result: Return
cash(7).
Proof of Correctness
The correctness relies on the principle of optimality. At any step i, the variable cash stores the absolute maximum profit achievable ending with 0 stocks, and hold stores the maximum profit achievable ending with 1 stock.
Since the transitions cover all possible actions (buy, sell, rest) and we greedily select the maximum value for each state, the final cash value must be the global maximum profit. The algorithm implicitly handles the "buy-sell-buy-sell" behavior by allowing the hold state to be funded by the cash state accumulated from previous transactions.
Pattern Reuse Notes
The "DP - Stock problems" pattern is highly reusable. The state machine approach (tracking hold vs cash) applies directly to variations of this problem:
- LeetCode 121: Best Time to Buy and Sell Stock (Restrict transactions to ).
- LeetCode 123: Best Time to Buy and Sell Stock III (Restrict transactions to , requiring 4 states).
- LeetCode 188: Best Time to Buy and Sell Stock IV (Generalize to transactions, using an array of states).
- LeetCode 309: Best Time to Buy and Sell Stock with Cooldown (Adds a third "cooldown" state to the state machine).
Mastering the state transition in LeetCode 122 is the foundation for solving the harder variants (III, IV, and Cooldown).
Feynman coach · Before you peek at the code
Can you explain the core insight in your own words?
If you can explain it before reading code, you’re far more likely to recall it under interview pressure.
Reference Implementation
C++ Solution for LeetCode 122
1class Solution {
2public:
3 int maxProfit(vector<int>& prices) {
4 if (prices.empty()) return 0;
5
6 // cash: max profit if we do not hold a stock at end of day
7 // hold: max profit if we do hold a stock at end of day
8 int cash = 0;
9 int hold = -prices[0];
10
11 for (int i = 1; i < prices.size(); ++i) {
12 // Update cash: either keep current cash or sell the stock we are holding
13 cash = max(cash, hold + prices[i]);
14
15 // Update hold: either keep holding or buy new stock with current cash
16 hold = max(hold, cash - prices[i]);
17 }
18
19 return cash;
20 }
21};Java Solution for LeetCode 122
1class Solution {
2 public int maxProfit(int[] prices) {
3 if (prices == null || prices.length == 0) {
4 return 0;
5 }
6
7 int cash = 0;
8 int hold = -prices[0];
9
10 for (int i = 1; i < prices.length; i++) {
11 // Either keep cash state, or sell current holding
12 int newCash = Math.max(cash, hold + prices[i]);
13
14 // Either keep hold state, or buy using accumulated cash
15 int newHold = Math.max(hold, cash - prices[i]);
16
17 cash = newCash;
18 hold = newHold;
19 }
20
21 return cash;
22 }
23}Python Solution for LeetCode 122
1class Solution:
2 def maxProfit(self, prices: List[int]) -> int:
3 if not prices:
4 return 0
5
6 # cash: max profit ending the day without stock
7 # hold: max profit ending the day with stock
8 cash = 0
9 hold = -prices[0]
10
11 for i in range(1, len(prices)):
12 # Store previous cash to ensure simultaneous update logic
13 prev_cash = cash
14
15 # Transition equations
16 cash = max(prev_cash, hold + prices[i])
17 hold = max(hold, prev_cash - prices[i])
18
19 return cash