Skip to main content
12

Best Time to Buy and Sell Stock

Easysliding windowarrays

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:Sliding WindowRead the beginner guide

prices[i] is the price of a stock on day i. You may buy once and then sell once on a later day.

Return the maximum profit you can make. If no trade makes money, return 0.

Understand the problem

  • Profit = sell price − buy price.
  • You must buy before you sell. You can't sell on day 2 and buy on day 5.
  • You make at most one trade (one buy, one sell). You may also choose not to trade at all, which gives a profit of 0.

Example 1

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

Buy on day 1 (price 1), sell on day 4 (price 6): 6 - 1 = 5. Buying at 1 and selling at 7 would be better, but 7 is on day 0, before the purchase, so it's not allowed.

Example 2

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

The price only goes down. Every trade loses money, so the best choice is not to trade.

Example 3

text
Input:  prices = [2, 4, 1]
Output: 2

Buy at 2, sell at 4. The lowest price, 1, comes last, so there's no later day to sell it on.

Constraints

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

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Walk through the days once, remembering the cheapest price so far, and on each day check how much you'd make by selling today.

    The naive approach (and why it's slow)

    Try every pair of days (buy on i, sell on a later j) and keep the best profit. That's about n × n / 2 pairs, O(n²). For 100,000 days, 5 billion pairs.

    The key insight

    Flip the question around. Instead of "which pair is best?", ask for each day: "if I sell today, what's the most I could make?"

    The answer: today's price minus the cheapest price on any earlier day. And we don't need to search for that cheapest price each time. We just keep a running minimum as we walk forward, which costs one comparison per day.

    This is the simplest form of a sliding window: the window stretches from the cheapest day to today, and its left edge jumps forward whenever we find a new lowest price.

    Step by step

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

    DayPriceProfit if I sell today (price - minPrice)Best profitminPrice afterwards
    077 - ∞ (nothing to buy yet)07
    111 - 7 = -601 (new low)
    255 - 1 = 441
    333 - 1 = 241
    466 - 1 = 551
    544 - 1 = 351

    Answer: 5.

    Notice the order inside each day: we check "sell today" before updating the minimum. That's what guarantees we always buy on an earlier day than we sell.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(n). One pass, constant work per day.
    • Memory: O(1). Just two numbers.

    Common mistakes

    • Using the global minimum and maximum. In [7, 1, 5, 3, 6, 4] the max is 7 and the min is 1, but 7 comes first, so 7 - 1 isn't a real trade.
    • Updating minPrice before computing the profit. It still works here (it just computes a profit of 0 for that day), but thinking "sell first, then maybe buy" keeps the logic honest in harder variants.
    • Returning a negative number when prices only fall. Starting best at 0 means "don't trade" is always an option.

    Going deeper

    There's a whole family of these problems: unlimited trades, at most two trades, a cooldown day, a fee per trade. They're usually solved with dynamic programming, tracking your best money in each state ("holding a stock" vs "not holding"). This problem is the simplest member of that family.

    Reference solution

    js
    /**
     * @param {number[]} prices
     * @return {number}
     */
    export default function maxProfit(prices) {
      let minPrice = Infinity // cheapest price seen so far (best day to have bought)
      let best = 0 // best profit so far; 0 means "don't trade"
      for (const price of prices) {
        // Sell today: buy at the cheapest EARLIER price. Check this first...
        best = Math.max(best, price - minPrice)
        // ...then maybe today is the new cheapest day to buy for a later sale.
        minPrice = Math.min(minPrice, price)
      }
      return best
    }
    ts
    export default function maxProfit(prices: number[]): number {
      let minPrice = Infinity // cheapest price seen so far (best day to have bought)
      let best = 0 // best profit so far; 0 means "don't trade"
      for (const price of prices) {
        // Sell today: buy at the cheapest EARLIER price. Check this first...
        best = Math.max(best, price - minPrice)
        // ...then maybe today is the new cheapest day to buy for a later sale.
        minPrice = Math.min(minPrice, price)
      }
      return best
    }
    python
    def max_profit(prices: list[int]) -> int:
        min_price = float("inf")  # cheapest price seen so far (best day to have bought)
        best = 0  # best profit so far; 0 means "don't trade"
        for price in prices:
            # Sell today: buy at the cheapest EARLIER price. Check this first...
            best = max(best, price - min_price)
            # ...then maybe today is the new cheapest day to buy for a later sale.
            min_price = min(min_price, price)
        return best