Skip to content
StackDecode
Array techniquesAnimated

Stock Buy and Sell

Track the lowest price so far and the best profit.

Time

O(n)

Extra space

O(1)

Use it for

Single-transaction maximum profit.

How it works

  1. Buy once, sell once later, maximise profit.
  2. Walk through the prices keeping the lowest price seen so far (the best day to have bought).
  3. At each day, profit if selling today = price − lowest so far.
  4. Keep the best profit. One pass, O(n).

Watch it run

Loading animation…