Best Time to Buy and Sell Stock II (LeetCode 122): Solution and Explanation

Medium
Array
Dynamic Programming
Greedy

You are given daily stock prices and may buy and sell as many times as you like, as long as you hold at most one share at a time. Return the largest total profit you can make.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A brute force would try every combination of buy and sell days, which is exponential. A cleverer first attempt finds each local valley and the next local peak and adds peak minus valley. That works, but there is an even simpler way to see the same answer.

Think about any profitable trade from day a to day b. Its profit prices[b] - prices[a] equals the sum of the daily changes between them. If some of those daily changes are negative, you would do better by skipping those days, because selling just before a drop and rebuying after it never loses money. Taken to the limit, the best strategy captures every single day where the price rises and avoids every day where it falls.

So the answer is simply the sum of prices[i] - prices[i - 1] over all days where that difference is positive. You do not even need to know which actual trades this corresponds to. A rising run from 1 to 5 contributes the same 4 whether you count it as one trade or four one-day trades, and the problem allows selling and buying on the same day in effect.

It helps to check the greedy claim against a tricky case. With prices [1, 2, 3, 4, 5], the code adds 1 four times for a total of 4, which equals buying on day 0 and selling on day 4. With prices [7, 6, 4, 3, 1], every difference is negative, nothing is added, and the answer is 0, which matches the rule that you are never forced to trade. Flat days add nothing either, so repeated prices never distort the total. This is one of the rare stock problems where a single pass with no state beyond a running total is provably optimal.

Approach: Greedy sum of positive differences

  1. Start with profit = 0.
  2. Loop over i from 1 to the last index.
  3. If prices[i] > prices[i - 1], add the difference to profit.
  4. Ignore days where the price stays the same or drops.
  5. Return profit after the loop.

Step-by-step example

prices = [7, 1, 5, 3, 6, 4]
  1. Day 1: price goes from 7 to 1, a drop, so nothing is added.
  2. Day 2: from 1 to 5, a rise of 4, so profit = 4.
  3. Day 3: from 5 to 3, a drop, skipped.
  4. Day 4: from 3 to 6, a rise of 3, so profit = 7.
  5. Day 5: from 6 to 4, a drop, skipped. The answer is 7, matching buy at 1, sell at 5, buy at 3, sell at 6.

Code: Python, Java, C++

1class Solution:
2    def maxProfit(self, prices: List[int]) -> int:
3        profit = 0
4        for i in range(1, len(prices)):
5            if prices[i] > prices[i-1]:
6                profit += prices[i] - prices[i-1]
7        return profit

Time and space complexity

Time

O(n)

Each adjacent pair of days is compared once.

Space

O(1)

Only the running profit is stored.

Other approaches

Two-state dynamic programming (time O(n), space O(1))

Track cash (no share) and hold (holding a share) for each day: cash = max(cash, hold + price) and hold = max(hold, cash - price). It gives the same answer and generalizes to fees and cooldowns.

Valley and peak scan (time O(n), space O(1))

Walk forward to each local minimum, then to the next local maximum, and add the difference. It mirrors real trades but needs more careful loop conditions.

Common mistakes

  • Trying to find only the single best buy and sell pair solves the one-transaction version and returns 5 instead of 7 on the example.
  • Starting the loop at 0 and reading prices[i - 1] wraps to the last element in Python, adding a bogus difference.
  • Adding abs(prices[i] - prices[i - 1]) counts drops as profit.
  • Overcomplicating with a full DP over transaction counts, which is unnecessary when transactions are unlimited.

Frequently asked questions

Why does summing positive differences give the maximum profit?

Any trade's profit equals the sum of the daily changes inside it. Including only the positive changes can never be worse than any set of trades, and every positive change can be captured by holding the stock for that one day.

Can you buy and sell on the same day?

You can sell and then buy on the same day in effect, which is why consecutive rising days can be merged or split freely without changing the total. You still never hold more than one share.

What is the difference between Stock I and Stock II?

Stock I allows one transaction, so you track the minimum price so far and the best single sale. Stock II allows unlimited transactions, so you collect every upward move.

Is there a DP solution?

Yes. Keep the best profit while holding and while not holding, and update both each day. It is the template that extends to the cooldown and transaction fee variants.