oneby7

1-D Dynamic Programming Buying and selling with states

537. Best Time to Buy and Sell Stock III

Hard

You are given an array prices, where prices[i] is the price of one share on day i. You may make at most two trades. A trade is buying one share on one day and selling it on a later day.

You can hold at most one share at a time, so the first trade must be sold before the second one is bought. Selling and buying again on the same day is allowed.

Return the largest total profit you can make. The profit of a trade is the selling price minus the buying price. You may also make one trade or none, and if no trade makes money, return 0.

Example 1

Input: prices = [3, 1, 7, 2, 9, 5, 6]

Output: 13

Explanation: Buy at 1 and sell at 7 for 6, then buy at 2 and sell at 9 for 7. The best single trade, from 1 to 9, makes only 8, and the rise from 5 to 6 would need a third trade.

Example 2

Input: prices = [0, 2, 5, 9, 10]

Output: 10

Explanation: The price never falls, so one trade from 0 to 10 is best. Splitting it into two trades earns nothing more.

Example 3

Input: prices = [9, 7, 7, 3]

Output: 0

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

Check your understanding

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

prices = [1, 5, 4, 8, 7, 11]

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.