DSA Visualizer · 25 visualizationsBest Time to Buy and Sell Stock
EasySliding Window

Best Time to Buy and Sell Stock

You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy and a different day in the future to sell. Return the maximum profit, or 0 if no profit is possible.

prices = [7, 1, 5, 3, 6, 4]Step 1 of 6
7
0l, r
1
1
5
2
3
3
6
4
4
5
min so far / best
min 7
best 0

Start on day 0 at price 7. The cheapest price so far is 7, so there is no profit yet.

Pythontime O(n) · space O(1)
1def maxProfit(prices):
2 min_price = prices[0]
3 best = 0
4 for i in range(1, len(prices)):
5 price = prices[i]
6 profit = price - min_price
7 if profit > best:
8 best = profit
9 if price < min_price:
10 min_price = price
11 return best
Variables
i—
price—
profit—
min7
best0

Problem

You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy and a different day in the future to sell. Return the maximum profit, or 0 if no profit is possible.

Examples

Input: prices = [7,1,5,3,6,4]Output: 5

Buy on day 2 (price=1), sell on day 5 (price=6)

Input: prices = [7,6,4,3,1]Output: 0

Prices only decrease, no profit possible

Constraints

  • 1 ≤ prices.length ≤ 10⁵
  • 0 ≤ prices[i] ≤ 10⁴

Intuition

The best day to sell is any day, and the best day to buy is the cheapest day before it. So sweep left to right keeping the minimum price seen so far; the best profit ending today is today's price minus that minimum.

Brute force → Optimal

Brute force

Try every buy day and every later sell day, and keep the largest profit.

Time O(n²)Space O(1)
Optimal

One pass. Track the minimum price so far; at each day compute price − min and keep the best.

Time O(n)Space O(1)

Complexity

Time O(n)Space O(1)

Edge cases

  • Fewer than two days: there is no future day to sell, so the answer is 0.
  • Prices that only fall, e.g. [7,6,4,3,1]: there is no profitable pair, so return 0.

Common mistakes

  • Buying and selling on the same day, which is not allowed — the sell day must come after the buy day.
  • Updating the minimum before computing today's profit, which would let a day pair with itself.
Two Sum is free. Enroll to unlock every visualization and save where you stopped.Enroll free