oneby7

1-D Dynamic Programming Buying and selling with states

536. Best Time to Buy and Sell Stock II

Medium

You are given an array prices, where prices[i] is the price of one share 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. So you must sell the share you hold before you buy another. You may sell a share and buy a new one on the same day.

Return the largest total profit you can make. The profit of one trade is its selling price minus its buying price. If no trade makes money, return 0.

Example 1

Input: prices = [6, 2, 5, 3, 9, 8, 11]

Output: 12

Explanation: Buy at 2 and sell at 5, buy at 3 and sell at 9, then buy at 8 and sell at 11. The three trades make 3 + 6 + 3 = 12. The best single trade, from 2 to 11, makes only 9.

Example 2

Input: prices = [9, 6, 6, 3, 0]

Output: 0

Explanation: The price never rises, so every trade loses money or breaks even. Not trading gives 0.

Example 3

Input: prices = [1000000000, 0, 1000000000, 0, 1000000000, 0, 1000000000]

Output: 3000000000

Explanation: Each of the three rises from 0 to 1000000000 is a trade worth making.

Check your understanding

Work out the answer for this input before you write any code.

prices = [3, 8, 4, 10, 6]

Constraints

  • 1 ≤ prices.length ≤ 105
  • 0 ≤ prices[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.