Loading
Loading
A hobby trader follows one commodity's daily closing price. She can hold at most one unit at a time, so she must sell before buying again. Her broker also enforces a rule: on the day after any sale, she may not buy.
Given the prices in day order, return the largest total profit she can make with any number of buy-sell rounds. Doing nothing earns 0.
prices = [1, 2, 3, 0, 2]day 0: buy at 1holdingday 1: sell at 2profit 1day 2: restbuying is not allowed todayday 3: buy at 0holdingday 4: sell at 2profit 1 + 2 = 33Sign 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 1, sell 2, rest on day 2, buy 0, sell 2: 1 + 2 = 3.
Example 2
Prices only fall, so the best plan is not to trade.