EasyArrayDynamic ProgrammingUpdated Sep 2026

121. Best Time to Buy and Sell Stock

Asked at Google, Meta, Amazon, Apple and 10 more

Difficulty

Easy

Time

O(n)

Space

O(1)

Pattern

Array

Companies

14

Problem

You get an array prices, where prices[i] is the price of one share of a stock on day i.

You may buy one share on some day, and later sell that share on a different, later day. You cannot sell before you buy, and you can only do this one time. Your profit is the sell price minus the buy price.

Return the largest profit you can make. If every possible buy-then-sell pair loses money, return 0 instead (meaning: do nothing).

Pick one buy day and a later sell day

prices715364012345Green is the buy day (price 1), orange is the sell day(price 6).profit = sell price - buy price6 - 1 = 5
Buying at price 1 on day 1 and selling at price 6 on day 4 gives the best profit, 5.

Constraints

  • ●1 <= prices.length <= 10^5
  • ●0 <= prices[i] <= 10^4

Examples

Example 1
Inputprices = [7,1,5,3,6,4]
Output5
WhyBuy on day 1 at price 1 and sell on day 4 at price 6. Profit = 6 - 1 = 5. Any other pair gives 5 or less.
Example 2
Inputprices = [7,6,4,3,1]
Output0
WhyPrices only fall, so every sell day is cheaper than every earlier buy day. No trade makes money, so the answer is 0.

Asked At

14 companies

How to Think About It

1

Brute force: try every possible buy day i and sell day j where j > i. Calculate profit = prices[j] - prices[i]. Track the maximum. That's O(n²) — too slow for large arrays.

2

Key insight: you don't need to track the buy day. Just track the minimum price seen so far. At each day, the best profit you can make by selling today is (today's price - minimum seen so far).

3

Why this works: if you know the minimum price up to today, selling today gives the maximum possible profit for that buy point. You don't care where the minimum was — you just need the value.

4

The invariant: min_price is always the cheapest price from day 0 to today. max_profit is always the best profit achievable from day 0 to today. Both update as you walk through the array.

5

Edge cases: prices always decreasing (never profitable — return 0), single price (can't sell — return 0), all same prices (no profit — return 0).

Optimal Approach

Initialize min_price = infinity and max_profit = 0. Iterate through prices:

  1. Update min_price = min(min_price, current price)
  2. Calculate profit = current price - min_price
  3. Update max_profit = max(max_profit, profit)

The key realization: you never need to know which day you bought on. You just need the minimum price up to today. By the time you sell, the buy decision is already made — you picked the cheapest day.

Time: O(n) — single pass. Space: O(1) — just two variables.

Track the cheapest day so far

prices715364012345todayDay 2: cheapest so far is 1, so selling today gives 5- 1 = 4.prices715364012345todayDay 4: cheapest is still 1, so selling today gives 6 -1 = 5, the best so far.min_price = min(min_price, price)profit = price - min_pricemax_profit = max(max_profit, profit)
At each day, the best profit from selling today uses the lowest price seen before it.
ComplexityTime O(n)Space O(1)One pass over the array, keeping only two numbers: the cheapest price so far and the best profit so far.

What Trips People Up in Real Interviews

1

Confusing "buy low, sell high" with "find the maximum difference." The sell must come after the buy — you can't sell before buying. This constraint makes it different from max subarray.

2

Trying to find the global minimum and global maximum. That doesn't work if the max comes before the min. You need to track the running minimum as you iterate from left to right.

3

Forgetting that you must buy before you sell. If all prices are decreasing, the answer is 0 (no profit), not the difference between the highest and lowest prices.

4

Not handling the edge case of a single price (return 0) or two prices where the second is lower (return 0).

5

Updating min_price only when max_profit improves. You must update min_price at every step independently — the cheapest day might appear well before the best selling opportunity, and skipping updates breaks the invariant.

Solution Code

O(n) time
def maxProfit(prices):
    min_price = float('inf')
    max_profit = 0
    for price in prices:
        min_price = min(min_price, price)
        max_profit = max(max_profit, price - min_price)
    return max_profit

Pro at DSA?

Test your skills with a real FAANG-style mock interview.

Start a Mock Interview →

Frequently Asked Questions

What is the Best Time to Buy and Sell Stock problem?

You are given an array where each element represents the price of a stock on a given day. Find the maximum profit you can achieve by buying once and selling once. This is a classic problem that tests whether you can think about optimal substructure.

How do you solve Best Time to Buy and Sell Stock?

The optimal approach runs in O(n) time and O(1) space. Scroll up to "Optimal Approach" for the step-by-step walkthrough, diagrams, and code in Python, C++ and Java.

What companies ask Best Time to Buy and Sell Stock?

Best Time to Buy and Sell Stock is asked at Google, Meta, Amazon, Apple, Microsoft, Oracle, Adobe, Atlassian, Salesforce, Walmart, Bloomberg, Goldman Sachs, NVIDIA, Flipkart. It is a easy difficulty problem.

What are common mistakes on Best Time to Buy and Sell Stock?
  • Confusing "buy low, sell high" with "find the maximum difference." The sell must come after the buy — you can't sell before buying. This constraint makes it different from max subarray.
  • Trying to find the global minimum and global maximum. That doesn't work if the max comes before the min. You need to track the running minimum as you iterate from left to right.
  • Forgetting that you must buy before you sell. If all prices are decreasing, the answer is 0 (no profit), not the difference between the highest and lowest prices.
  • Not handling the edge case of a single price (return 0) or two prices where the second is lower (return 0).
  • Updating min_price only when max_profit improves. You must update min_price at every step independently — the cheapest day might appear well before the best selling opportunity, and skipping updates breaks the invariant.