InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Sliding Window

Best Time to Buy and Sell Stock

easy Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug