TRT
Sign in
easyAdvancedLeetCode#running-minimum#one-pass

Best Time to Buy and Sell Stock

Choose one buy day and a later sell day to maximize positive profit; return zero if no profitable trade exists.

The Runtime Theory Team25 min read
Taught inCache-Conscious Data Structures: Alignment, False Sharing, and Structure of ArraysPro — members onlyStructure C data layouts for CPU cache lines, eliminate multi-core false sharing with explicit alignment, and transform Array of Structures into Structure of Arrays for SIMD saturation.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inprices=[7,1,5,3,6,4]

out5

inprices=[7,6,4,3,1]

out0

inprices=[2,4,1]

out2

Pick one day to buy and a later day to sell so the profit is as large as possible; return 0 when no profitable trade exists.

Before you code

Pairing every buy with every later sell is quadratic. The order of days does the work for you: for each sell day, the best partner is the cheapest day before it, so tracking that cheapest day as you go is enough.

Hints

  1. Scan left to right holding the lowest price seen so far.
  2. Treat each day as a possible sell day: profit_today = price - lowest_before, and remember the best value seen.
  3. Never let a day buy and sell to itself — compare first, then update the lowest price — and never return a negative number when prices only fall.

Production & complexity notes

When solving Best Time to Buy and Sell Stock on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Cache-Conscious Data Structures: Alignment, False Sharing, and Structure of Arrays to reinforce the underlying pattern.

What it practices

One running aggregate over each prefix instead of re-scanning the past, from Prefix sums.

Not started

Sign in to save your learning progress.

Sign in to save