InterviewPrepKit

Home / Coding / Arrays & Hashing

Best Time to Buy and Sell Stock II

medium Original β†—
Solving tips
  • Unlimited transactions with same-day rebuy means any long trade telescopes into a chain of one-day trades, so the answer is just the sum of positive consecutive differences.
  • Greedy: sum max(prices[i+1] - prices[i], 0) in one O(n) pass, O(1) space.
  • Don't reuse Stock I's single-trade min/max logic; it undercounts here since multiple trades are allowed.
  • If greedy feels risky, the two-state hold/cash DP is the safe fallback and generalizes to cooldown/fee/k-trade variants; never return a negative (doing nothing gives 0).

Problem

You’re given prices, where prices[i] is a stock’s price on day i. You may buy and sell as many times as you like, but you can hold at most one share at a time β€” you must sell before buying again. Selling and re-buying on the same day is allowed.

Return the maximum total profit you can achieve. (Doing nothing, for profit 0, is always allowed.)

Examples

  • prices = [7, 1, 5, 3, 6, 4] β†’ 7 β€” buy at 1, sell at 5 (+4); buy at 3, sell at 6 (+3).
  • prices = [1, 2, 3, 4, 5] β†’ 4 β€” one trade from 1 to 5 (or equivalently a sell-and-rebuy every day; same total).
  • prices = [7, 6, 4, 3, 1] β†’ 0 β€” prices only fall; never buying beats any trade.

Constraints

  • 1 <= prices.length <= 3 * 10^4
  • 0 <= prices[i] <= 10^4

Trying every combination of trades is exponential; with 3Β·10^4 days you need a linear (or near-linear) answer.

Think about it first

Hint 1 Because you may re-buy the same day you sell, a long trade from day i to day j earns exactly the same as a chain of one-day trades iβ†’i+1→…→j. What does that let you decompose the problem into?
Hint 2 Look at each consecutive pair of days independently. When is the one-day trade from day i to day i+1 worth taking?
Hint 3 Sum `prices[i+1] - prices[i]` over every day where that difference is positive β€” every profitable trade decomposes into (and never beats) this sum of positive daily gains.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.