Loading
Loading
A commodity's price is recorded once per day. You may buy on one day and sell on a strictly later day, at most once.
Return the largest profit achievable. If no pair of days yields a profit, return 0.
prices = [7, 1, 5, 3, 6, 4]day 0 (7)cheapest so far = 7, profit 0day 1 (1)cheapest so far = 1day 2 (5)sell at 5 → profit 4day 4 (6)sell at 6 → profit 5, the best5Sign in to keep a note here. It is free, and nobody else can see it.
Sign inExample 1
Sign in to open hints.
Struggling is where the learning happens. Open this once you have genuinely tried, or once the hints have run out.
O(n) time · O(1) space
Input. Run your code to watch it work on this input, one line at a time.
Running code is turned off on this deployment. You can still read the problem, write code, use hints and the visualizer.
Tab moves focus out of the editor. Press Ctrl+M to let Tab indent instead.
No results yet
Run your code against the sample tests, or submit to run the full suite.
Buy at 1 on day 1, sell at 6 on day 4.
Example 2
Prices only fall, so no trade is profitable.