← DSA
EASY

Best Time to Buy and Sell Stock

PracticeNeetCode ↗LeetCode ↗

Given an array prices where prices[i] is the price of a stock on day i, find the maximum profit from buying on one day and selling on a later day. Return 0 if no profit is possible.

Example

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

Key Pointers

Step-by-Step Analysis

  1. Initialize min_price to infinity and max_profit to 0.
  2. For each price: if it's lower than min_price, update min_price.
  3. Otherwise, compute profit = price - min_price and update max_profit if it's larger.
  4. Return max_profit.

Complexity

Time: O(n) — Space: O(1)

Code

def maxProfit(prices: list[int]) -> int:
    min_price = float('inf')
    max_profit = 0
    for price in prices:
        if price < min_price:
            min_price = price
        else:
            max_profit = max(max_profit, price - min_price)
    return max_profit

Code Explanation

How the solution above works, piece by piece.

  1. min_price = the cheapest day so far (the best day to have bought); max_profit starts at 0 because not trading is allowed.
  2. For each day: if today's price is a new minimum, update min_price. Selling on the day you buy earns nothing, so there's nothing else to do.
  3. Otherwise, selling today would earn price - min_price; keep it if it beats the best so far.
  4. One pass, two variables: O(n) time, O(1) space.

Visual Walkthrough

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

Prices over six days with buy at 1 and sell at 67day 01day 15day 23day 36day 44day 5buy (min so far)sell: 6 − 1 = 5min_price 7 1 1 1 1 1max_profit 0 0 4 4 5 5
Walking left to right, the code only needs the cheapest price seen so far. Selling today earns price − min_price; the best of those is the answer. Buying must come before selling, which the left-to-right order guarantees.
buysell

Video Explanation

Striver (takeUforward) — Best Time to Buy and Sell Stock, Brute-Optimal