Skip to content
Decoder

Best Time to Buy and Sell Stock II

Medium

Problem

prices[i] is a share 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 may buy and sell on the same day. Return the largest total profit you can make.

Example 1

Input
prices = [7, 1, 5, 3, 6, 4]
Output
7
Why
buy 1 sell 5, buy 3 sell 6

Example 2

Input
prices = [1, 2, 3, 4, 5]
Output
4
Why
buy 1 sell 5, or sell every day

Example 3

Input
prices = [7, 6, 4, 3, 1]
Output
0
Why
never trade

Constraints

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

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.