InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Best Time to Buy and Sell Stock II

medium Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug