Given an array `prices` where `prices[i]` is the price on day i, return the maximum profit from buying on one day and selling on a later day. If no profit is possible, return 0.
Example: prices = [7, 1, 5, 3, 6, 4] → 5 (buy at 1, sell at 6)
Brute force: Try every buy/sell pair and keep the best profit. (time O(n²), space O(1))
No visualization loaded.
Watch
—
i
Press Run to begin.
0/0
Why the best approach wins
Brute force re-examines every earlier day for each sell day — O(n²). But you only ever need the cheapest price seen so far: scan once, update the running minimum, and the best profit at each step is today's price minus that minimum. One O(n) pass, O(1) memory.
Brute force: O(n²) time / O(1) spaceOne pass (min so far): O(n) time / O(1) space
Your turn — implement maxProfit
Loading editor…