15% off all plans & roadmaps Use code

See plans

Best Time to Buy and Sell Stock

Updated

TL;DR: Pick one buy day and a later sell day to maximize profit, or return 0. Scan once, track the lowest price seen so far, and record the best gap between today's price and that low.

Problem

You are given an array prices, where prices[i] is the price of a stock on day i.

You may complete one transaction: choose one day to buy a single share and a different, later day to sell it. Return the maximum profit you can make. If no profitable transaction exists, return 0.

Example 1

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price 1) and sell on day 5 (price 6) for a profit of 6 - 1 = 5. Buying on day 2 and selling on day 1 is not allowed, because the sale must come after the purchase.

Example 2

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: Prices only fall, so no transaction makes money. You make none, and the answer is 0.

Constraints

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

Constraints that matter

  • prices.length up to 10^5 rules out checking every buy and sell pair. That is about 5 * 10^9 pairs, far too slow, so you need a linear scan.
  • 1 <= prices.length means the array is never empty, so reading prices[0] is safe. A single price gives no sell day, so the answer is 0.
  • prices[i] >= 0 means every difference fits easily in a 32-bit int. The largest possible profit is 10^4, so Java and C# need no long.
  • prices[i] <= 10^4 lets you start a running minimum at a large sentinel such as 10^4 + 1 or at prices[0]. Either works without overflow risk.
  • The answer must be at least 0, so the best-profit variable starts at 0 and never goes negative.

View on LeetCode

Hints

Hint 1

This is a single pass with a running minimum, the lightest form of the stock-problems DP pattern.

Hint 2

Try every legal transaction.

Solution

Intuition

This is a single pass with a running minimum, the lightest form of the stock-problems DP pattern. The state you carry is tiny: the cheapest price so far and the best profit so far.

Picture walking along a ridge trail and remembering the lowest point you have passed so far. At each step you note how far you have climbed above that low point and keep the biggest climb, so min_price is the remembered low, best is the biggest climb, and you never go back to re-measure earlier spots.

The key observation is about the sell day. Fix a sell day i. The best buy day for it is the cheapest day before i, and nothing else matters. You do not need to compare day i against every earlier day, only against the minimum of them.

So the answer is the maximum over all days i of prices[i] - min(prices[0..i]). Every candidate transaction is covered. Each possible sell day gets its best partner, and the true optimum has some sell day, so the maximum of these values is the optimum.

Order matters because you must buy before you sell. Scanning left to right and updating the minimum as you go enforces that for free. When you reach day i, the minimum you hold only includes days at or before i, so you can never sell before you buy.

A common wrong idea is to take the global minimum and global maximum and subtract. That fails when the maximum comes first, as in [5, 1]. The scan avoids this because it never pairs a price with a low that appears later.

Watch the pattern animation

Worked example

Input: prices = [3, 8, 1, 9, 2, 10, 1, 11]
Output: 10
Explanation: The lowest price is 1, and the highest price after a 1 is 11 on the last day. Buying at 1 and selling at 11 gives 10. Buying at 3 and selling at 11 gives only 8, so a later, lower buy day wins.

Approach 1: Brute force

Try every legal transaction. For each buy day i, try every sell day j after it, compute prices[j] - prices[i], and keep the largest value. Start the answer at 0 so a falling market returns 0.

This is correct because it enumerates every allowed pair. You can write it in a minute, and it is the baseline to improve.

Steps

  1. Set best = 0.
  2. For each buy day i from 0 to n - 1, loop over each sell day j from i + 1 to n - 1.
  3. Compute profit = prices[j] - prices[i].
  4. If profit > best, set best = profit.
  5. After both loops finish, return best.

Dry run

On [3, 8, 1, 9, 2, 10, 1, 11] the outer loop picks each buy day in turn and the inner loop finds the best sell price after it.

Buy day iPriceBest later priceBest profit for this buyRunning best
031188
181138
21111010
3911210
4211910
51011110
61111010
711none010

The final running best is 10.

Complexity

TimeO(n^2)
SpaceO(1)

Let n be the length of prices. The outer loop runs n times and the inner loop runs n - 1 - i times for buy day i. The total number of pairs is n * (n - 1) / 2, which is O(n^2). With n = 10^5 that is about 5 * 10^9 comparisons, too slow for typical limits. Only a few integer variables are stored, so space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        n = len(prices)
        best = 0
        for i in range(n):
            for j in range(i + 1, n):
                profit = prices[j] - prices[i]
                if profit > best:
                    best = profit
        return best

Approach 2: Prefix minimum array

What's slow: the inner loop re-scans every later day for each buy day. Most of that work repeats, because for a given sell day only the cheapest earlier price matters.

The insight that fixes it: precompute low[i], the minimum of prices[0..i], in one pass using low[i] = min(low[i-1], prices[i]). Then the best profit for selling on day i is prices[i] - low[i]. A second pass takes the maximum of those values. This is the DP form: each entry is built from the previous entry in constant time.

Steps

  1. Create an array low of the same length as prices.
  2. Set low[0] = prices[0].
  3. For i from 1 to n - 1, set low[i] = min(low[i-1], prices[i]).
  4. Set best = 0.
  5. For each i, compute prices[i] - low[i] and keep the larger of it and best.
  6. Return best.

Dry run

On [3, 8, 1, 9, 2, 10, 1, 11] the first pass builds low = [3, 3, 1, 1, 1, 1, 1, 1].

The second pass subtracts: 3-3=0, 8-3=5, 1-1=0, 9-1=8, 2-1=1, 10-1=9, 1-1=0, 11-1=10. The largest value is 10, which is the answer.

Complexity

TimeO(n)
SpaceO(n)

Let n be the length of prices. The first loop does one min comparison per index and the second does one subtraction and comparison per index. The work is 2n constant-time steps, which is O(n). The low array holds n integers, so space is O(n). The array is not needed, as the next approach shows.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        n = len(prices)
        low = [0] * n
        low[0] = prices[0]
        for i in range(1, n):
            low[i] = min(low[i - 1], prices[i])
        best = 0
        for i in range(n):
            best = max(best, prices[i] - low[i])
        return best
Stock problems pattern infographic for Best Time to Buy and Sell Stock

Solution pattern

Stock problems

Part of Dynamic Programming (DP) Patterns

Approach 3: One pass with running minimumOptimalStock problems

What's slow: the prefix array stores n values, yet each step reads only the previous entry. The memory is wasted, and two passes are unnecessary.

The insight that fixes it: merge both loops and keep a single variable min_price instead of the array. At each day, first test whether selling today beats best, then lower min_price if today is cheaper. One loop, two variables. You can also see this as a sliding window: the left edge is the buy day, the right edge is the sell day, and the left edge jumps to the right edge whenever a new low appears.

Steps

  1. Set min_price = prices[0] and best = 0.
  2. Loop over each price in prices.
  3. If price < min_price, set min_price = price, because a cheaper buy day appeared.
  4. Otherwise compute price - min_price and update best if it is larger.
  5. Return best after the loop.

Dry run

Trace on [3, 8, 1, 9, 2, 10, 1, 11]. The candidate column is price - min_price using the minimum after processing that day.

DayPricemin_price afterCandidatebest after
03300
18355
21105
39188
42118
510199
61109
71111010

The loop ends with best = 10, which matches the expected output. On day 2 the price 1 becomes the new buy day, and every later sale is measured against it.

Complexity

TimeO(n)
SpaceO(1)

Let n be the length of prices. The loop runs exactly n times and each iteration does one comparison, at most one subtraction and one assignment, so time is O(n). Only min_price and best are stored, independent of n, so space is O(1). This is optimal for time because any correct answer must read every price at least once.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_price = prices[0]
        best = 0
        for price in prices:
            if price < min_price:
                # a cheaper buy day for all later sales
                min_price = price
            elif price - min_price > best:
                best = price - min_price
        return best

Common mistakes

  • Subtracting min(prices) from max(prices). The minimum can come after the maximum, as in [5, 1], which would give 4 instead of 0. Pair each sell day only with a low from earlier days.
  • Starting best at float('-inf'), Integer.MIN_VALUE or prices[0] - prices[1]. The problem says to return 0 when no profit exists, so start best = 0 and let it only grow.
  • Updating min_price with prices[i] before computing the profit and then using the same day as both buy and sell. That gives 0 for that day, which is harmless, but in a version that tracks indexes it can allow same-day trades. Compute the candidate from the minimum of earlier days or accept the 0.
  • Initializing min_price = 0. Then every price minus 0 equals the price itself and the answer becomes the maximum price. Start from prices[0] or a large sentinel like float('inf') or INT_MAX.
  • Running nested loops and expecting them to pass. With 10^5 prices that is about 5 * 10^9 pair checks, which times out. Replace the inner loop with the running minimum.
  • Resetting best when a new minimum appears. A new low only changes the future buy price, and profits already found remain valid. Keep best untouched in that branch.

Edge cases

  • [5]: one day, no sell day exists. Return 0.
  • [7, 6, 4, 3, 1]: strictly decreasing, so no profit is possible. Return 0.
  • [1, 2, 3, 4, 5]: strictly increasing. Buy on the first day and sell on the last for 4.
  • [2, 2, 2, 2]: all equal prices give differences of 0. Return 0.
  • [5, 1] or [10, 1, 2]: the global max comes before the global min. The answer must come from the later segment, here 0 and 1.
  • [0, 10000] and an array of 10^5 prices: the largest value is 10^4 and fits in an int, and the scan must finish in linear time.

Follow-ups interviewers ask

What if you may complete as many transactions as you like (Best Time to Buy and Sell Stock II)?
Capture every upward step. Sum max(0, prices[i] - prices[i-1]) over all days. This works because any multi-day rise equals the sum of its daily rises, and you skip every fall. It runs in O(n) time and O(1) space.
How would you also return the buy day and sell day, not only the profit?
Track the index of the current minimum alongside its value. When a candidate beats best, record the stored minimum index as the buy day and the current index as the sell day. The loop stays O(n) and the extra state is three integers.
What if you may make at most two or at most k transactions?
A single running minimum is no longer enough, so you track a state per transaction. For two transactions keep buy1, sell1, buy2 and sell2 and update them in order each day. For k transactions use a DP table of size k by n, or k by 2 with rolling state, giving O(n * k) time.

Best Time to Buy and Sell Stock FAQ

What is the time complexity of Best Time to Buy and Sell Stock?

The optimal one-pass solution is O(n) time and O(1) space, where n is the number of days. The brute force version is O(n^2) because it checks every buy and sell pair. The prefix minimum array version is O(n) time and O(n) space.

Why use a running minimum for Best Time to Buy and Sell Stock?

For any sell day, the best buy day is the cheapest day before it. A running minimum gives that value in constant time, so each day needs one subtraction instead of a scan over all earlier days. That turns O(n^2) into O(n).

Can Best Time to Buy and Sell Stock be solved in O(1) extra space?

Yes. The one-pass solution stores only min_price and best. The prefix minimum array is only a stepping stone and can be dropped because each entry depends only on the previous one.

Is LeetCode 121 a dynamic programming, greedy or sliding window problem?

It fits all three views. The DP view says the best profit ending on day i depends on the minimum up to day i. The greedy view says to keep the cheapest buy so far. The sliding window view moves the left edge to the right edge on each new low. The code is identical.

What should I return if the prices only go down?

Return 0. The problem lets you skip the transaction, so negative profit is never reported. Initializing best = 0 handles this without a special case.

When should I buy and sell shares in real life, and what are the 7% sell rule and 10am rule?

This problem is not trading advice. It assumes you already know every future price, so the best buy and sell days are knowable. Real markets give no such information. The 7% sell rule and the 10am rule are trader rules of thumb, and nothing in the LeetCode solution depends on them.

Asked at

See which companies ask this — Pro

Practise it