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
- Buy once, sell once later, maximise profit.
- Walk through the prices keeping the lowest price seen so far (the best day to have bought).
- At each day, profit if selling today = price − lowest so far.
- Keep the best profit. One pass, O(n).
Watch it run
Loading animation…