codebrew.ai

Best Time to Buy and Sell Stock

Track the cheapest price so far and the best profit against it.

Approach

Sweep once, keeping the minimum price seen. At each day, the best sale is today's price minus that running minimum; keep the largest such difference. It's a one-pass sliding view of 'buy low before, sell here'.

Time complexity

O(n)

Space complexity

O(1)

Common mistake

Comparing every buy/sell pair (O(n²)) instead of tracking the running minimum.

See it run, step by step

Generate an interactive lesson for Best Time to Buy and Sell Stock — trace every variable and watch the algorithm execute until it clicks.

Start a lesson on Best Time to Buy and Sell Stock

Related problems