‹ DS&A interview · Socratic
DSA · Greedy / one pass · #22

Best Time to Buy and Sell Stock

Module 25 · difficulty 1/5·30:00starts on first keystroke

You are given an array `prices` where `prices[i]` is the price of a given stock on day `i`. Maximize profit by choosing a single day to buy and a later day to sell. Return the maximum profit; if no profit is possible, return `0`.

Examples
  • prices = [7,1,5,3,6,4] 5buy at 1, sell at 6
  • prices = [7,6,4,3,1] 0prices only fall
  • prices = [2,4,1] 2

Stuck? Reveal an animated walkthrough of the approach.

Constraints
  • · 1 <= prices.length <= 10^5
  • · 0 <= prices[i] <= 10^4
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.