oneby7

1-D Dynamic Programming Buying and selling with states

535. Best Time to Buy and Sell Stock IV

Hard

You are given an integer k and an array prices, where prices[i] is the price of one share on day i. You may make at most k trades. You can hold at most one share at a time, so you must sell the share you hold before you buy again.

A trade is one buy and the sale that follows it. The buy and the sale together count as one trade, not two.

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

Example 1

Input: k = 2, prices = [3, 2, 6, 5, 8, 1, 4]

Output: 9

Explanation: Buy at 2 and sell at 8 for 6, keeping the share through the dip to 5. Then buy at 1 and sell at 4 for 3 more. Selling at 6 and buying again at 5 would need a third trade.

Example 2

Input: k = 5, prices = [8, 0, 5, 5, 2]

Output: 5

Explanation: Buy at 0 and sell at 5. The price never rises again, so the other four trades stay unused.

Example 3

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

Output: 3000000000

Explanation: The price rises by 109 four times, but only three trades are allowed.

Check your understanding

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

k = 1, prices = [2, 6, 4, 9]

Constraints

  • 1 ≤ k ≤ 100
  • 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.