Best Time to Buy and Sell Stock II
You may buy and sell a stock as many times as you like, holding at most one share at a time. Return the maximum profit.
Open on LeetCode ↗Intuition
With unlimited transactions there is no need to identify the 'right' valleys and peaks. Any profitable hold from day i to day j yields exactly the same money as buying and selling on every single day in between — the intermediate prices cancel telescopically. So the maximum profit is simply the sum of every positive day-to-day change. Days where the price falls are avoided by holding nothing, costing nothing.
Approach
See why peak-and-valley detection is unnecessary
The instinct is to find each local minimum, buy, find the next local maximum, sell. That works, but consider prices 1, 5 versus 1, 3, 5. Buying at 1 and selling at 5 earns 4. Buying at 1 selling at 3, then buying at 3 selling at 5, also earns 2 + 2 = 4. The sums are identical because the intermediate price appears once positively and once negatively. So a long hold and a chain of one-day holds are interchangeable.
Reduce it to summing positive deltas
If every profitable hold can be decomposed into consecutive single-day holds, then the total profit is the sum of prices[i] - prices[i-1] over all days where that difference is positive. Negative differences are simply skipped — on a falling day we hold no stock and lose nothing. No state, no lookahead, one pass.
Note the DP formulation, and why the greedy is preferred here
The general framing tracks two states per day: hold (maximum profit while owning a share) and free (maximum while owning none), with hold = max(hold, free - price) and free = max(free, hold + price). That machinery is required for the k-transaction and cooldown variants. For unlimited transactions it provably reduces to the delta sum, so state the DP to show you know the general pattern, then implement the one-liner.
Solution & live demo
Edge cases
No delta is positive, so the profit is 0 — the correct answer, since making no trade is always allowed.
Every delta is positive and their sum telescopes to prices[-1] - prices[0], matching a single buy-and-hold.
The loop never runs and the profit is 0 — you cannot buy and sell on the same day.
A zero delta contributes nothing and is correctly ignored.