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

Easy
Array
Dynamic Programming

You get a list of daily stock prices. Pick one day to buy and a later day to sell so the profit is as large as possible, and return that profit, or 0 if no trade makes money.

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

Intuition

The brute force checks every buy day against every later sell day and keeps the largest difference. That is O(n²). To get faster, ask what you actually need to know on each potential sell day. The best trade that sells today must have bought at the lowest price seen on any earlier day. You do not care which day it was or what happened in between, only the minimum so far.

So a single left-to-right pass is enough. Keep track of the cheapest day so far as your buy candidate. For each new day, if the price is higher than the buy price, compute the profit you would make selling today and update the best profit. If the price is lower or equal, today becomes the new buy candidate, because any future sale will do at least as well buying here as buying at the old minimum.

The reference solution phrases this as a sliding window with two pointers. l is the buy day and r is the sell day being considered. When prices[l] < prices[r] the window is profitable and you record its profit. Otherwise you jump l all the way to r, starting a fresh window at the new low. Since r advances every iteration and l only ever jumps forward, the pass is linear.

Approach: Sliding window with a running minimum

  1. Initialize the buy pointer l = 0, the sell pointer r = 1 and maxP = 0.
  2. While r < len(prices), compare prices[l] with prices[r].
  3. If prices[l] < prices[r], compute profit = prices[r] - prices[l] and update maxP = max(maxP, profit).
  4. Otherwise prices[r] is a new low (or tie), so set l = r.
  5. Increment r and repeat.
  6. Return maxP, which stays 0 if prices never rise.

Step-by-step example

prices = [7, 1, 5, 3, 6, 4]
  1. l = 0, r = 1: 7 is not less than 1, so the buy day moves to l = 1.
  2. r = 2: buy at 1, sell at 5, profit 4. maxP = 4.
  3. r = 3: profit 3 - 1 = 2, maxP stays 4.
  4. r = 4: profit 6 - 1 = 5, maxP = 5.
  5. r = 5: profit 4 - 1 = 3, maxP stays 5. The loop ends and the answer is 5 (buy on day 1 at price 1, sell on day 4 at price 6).

Code: Python, Java, C++

1class Solution:
2    def maxProfit(self, prices: List[int]) -> int:
3        l, r = 0, 1
4        maxP = 0
5        
6        while r < len(prices):
7            if prices[l] < prices[r]:
8                profit = prices[r] - prices[l]
9                maxP = max(maxP, profit)
10            else:
11                l = r
12            r += 1
13            
14        return maxP

Time and space complexity

Time

O(n)

The sell pointer r moves forward exactly once per iteration, so the loop runs n - 1 times with constant work each.

Space

O(1)

Only two indices and the best profit are stored.

Other approaches

Brute force over all pairs (time O(n²), space O(1))

For each buy day, scan every later day and track the maximum difference. Correct but quadratic, so it times out on 10^5 prices.

Kadane on daily differences (time O(n), space O(1))

Convert prices to day-over-day changes and find the maximum subarray sum, since a buy and sell pair is a sum of consecutive changes. It shows the link to Maximum Subarray but is less direct than tracking the minimum.

Common mistakes

  • Taking the global minimum and global maximum and subtracting. If the maximum comes before the minimum, as in [7, 1], that trade is impossible and the answer is 0.
  • Returning a negative profit when prices only fall. The problem allows not trading, so the answer should never be below 0, which is why maxP starts at 0.
  • Moving the buy pointer only by one step instead of jumping to r. The new low is at r, so l must move there directly.
  • Confusing this with the unlimited-transactions version. Here you may make exactly one buy and one sell, so summing every upward move gives the wrong answer.

Frequently asked questions

How do you solve Best Time to Buy and Sell Stock in O(n)?

Track the lowest price seen so far while scanning. On each day, the best profit from selling that day is the price minus that minimum, so one pass finds the overall maximum.

Is this a sliding window or dynamic programming problem?

Both views work. As a sliding window, the left pointer is the buy day and jumps to any new low. As dynamic programming, the state is the minimum price so far and the best profit so far.

What if prices only go down?

No profitable trade exists, so the function returns 0. The buy pointer keeps moving to each new low and maxP is never updated.

What about buying and selling multiple times?

That is a different problem, where you add up every positive day-to-day increase. Versions with a cooldown or a limit of k trades need dynamic programming.