InterviewPrepKit

Home / Coding / Sliding Window

Best Time to Buy and Sell Stock

easy Original β†—
Solving tips
  • Reframe it: for each sell day the best buy is the cheapest price seen so far, so one left-to-right pass suffices instead of checking all pairs.
  • Key insight: track min_price seen so far and the best profit = current price - min_price; update min when a lower price appears.
  • Target O(n) time and O(1) space; the O(n^2) all-pairs brute force is too slow at n=1e5.
  • Common pitfall: never sell before you buy (max(prices)-min(prices) is wrong), and initialize best=0 so a strictly decreasing array returns 0.

Problem

You are given an array prices where prices[i] is the price of a stock on day i. You may make at most one transaction: pick one day to buy a single share and a later day to sell it. Return the maximum profit you can achieve. If no profitable transaction exists (prices only fall), return 0 β€” you are allowed to skip trading entirely.

Note the ordering constraint: the sell day must come strictly after the buy day. You cannot sell first and buy later.

Examples

  • prices = [7, 1, 5, 3, 6, 4] β†’ 5 β€” buy at 1 (day 1), sell at 6 (day 4); profit 6 - 1 = 5.
  • prices = [7, 6, 4, 3, 1] β†’ 0 β€” prices only decline, so the best move is not to trade.
  • prices = [2, 4, 1, 7] β†’ 6 β€” buy at 1 (day 2), sell at 7 (day 3); note the tempting 2 β†’ 4 early pair is worse.

Constraints

  • 1 <= len(prices) <= 10^5
  • 0 <= prices[i] <= 10^4

With up to 10^5 days, checking every buy/sell pair (~5 * 10^9 pairs in the worst case) is too slow β€” the expected solution is a single pass.

Think about it first

Hint 1 For a fixed sell day, which buy day maximizes profit? You never need to consider more than one candidate.
Hint 2 Sweep left to right, keeping track of the cheapest price seen so far. At each day, the best profit selling today is today - cheapest_so_far.
Hint 3 As a two-pointer window: left is the buy day, right the sell day. If prices[right] < prices[left], no future sale ever benefits from buying at left instead of right β€” jump left to right. Otherwise record the profit and advance right.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.