Best Time to Buy and Sell Stock II

MediumGreedygreedy

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

prices[i] is the price of one share on day i. You may complete as many buy/sell transactions as you like, but you can hold **at most one share** at any moment, so you must sell before buying again. Selling and buying again on the same day is allowed. Return the maximum total profit you can earn. If no trade makes money, return 0.

Examples

Input: prices = [7,1,5,3,6,4]
Output: 7
Buy at 1 and sell at 5 (+4), then buy at 3 and sell at 6 (+3).
Input: prices = [1,2,3,4,5]
Output: 4
Buy on day 0 and sell on day 4; splitting into daily trades gives the same 4.
Input: prices = [7,6,4,3,1]
Output: 0
Prices only fall, so the best plan is to never trade.

Constraints

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

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More greedy problems