prices = [7, 1, 5, 3, 6, 4]→ 5Buy at 1 and sell later at 6; their difference is 5.
Given daily stock prices, choose one day to buy and a later day to sell. Return the largest possible non-negative profit; return zero when no profitable trade exists.
prices = [7, 1, 5, 3, 6, 4]→ 5Buy at 1 and sell later at 6; their difference is 5.
prices = [7, 6, 4, 3, 1]→ 0Every later price is lower, so skipping the trade is best.
prices = [2, 4, 1]→ 2The later low price cannot erase the earlier valid gain from 2 to 4.
Try every buy day with every later sell day and keep the largest positive difference. This checks the ordering rule directly, but costs O(n²) time and O(1) extra space.
Scan prices from left to right. Before treating today as a possible new low, compare today’s price with the cheapest earlier buy price. Update the best profit, then update the running minimum. This considers the best legal purchase for every possible sale day.
Before processing day i, minimum is the cheapest price among days before i and best is the largest legal profit using sale days before i. Comparing today with minimum covers every trade ending today; updating minimum prepares the next day without allowing a same-day future sale.
Each price is read once, so the scan takes O(n) time and O(1) extra space. The pair-check baseline takes O(n²) time and O(1) extra space.
For [2, 4, 1], a low price of 1 appears after the profitable sale at 4. Resetting the best profit when the minimum falls would incorrectly return zero instead of two.
Each day can be a sale day. Compare it with the cheapest earlier buy, then update the minimum for tomorrow.
Day 0: price 7. Cheapest earlier: none yet.
Today’s profit: no legal sale yet · best so far: 0 · next minimum: 7
Day 0 becomes the first possible buy day. No sale is possible yet.This check gives feedback. Only a separate code pass records an independent solve.
Write solve(data). data.prices is an array of non-negative integers. Return the largest profit from one buy before one sell, or zero. The checks include falling prices, short histories, empty input, and fresh histories.
Opening the code studio…
Loading your saved attempts…
This lesson uses original explanations and examples. For additional practice, see the related LeetCode challenge.