oneby7

2-D Dynamic Programming Splitting a range

575. Minimum Cost to Cut a Stick

Hard

You have a wooden stick of length n, marked from 0 at one end to n at the other. The array cuts lists the marks where the stick must be cut. You make the cuts one at a time, in any order you choose.

A cut splits one piece of the stick into two, and it costs the length of that piece at the moment you cut it. So the same cut can cost more or less depending on which cuts were made before it.

Return the smallest total cost of making every cut in cuts.

Example 1

Input: n = 10, cuts = [7, 2, 4]

Output: 20

Explanation: Cut at 4 first, for 10. Then cut the piece from 0 to 4 at 2, for 4, and the piece from 4 to 10 at 7, for 6. That is 20. Cutting from left to right would cost 10 + 8 + 6 = 24.

Example 2

Input: n = 7, cuts = [3]

Output: 7

Explanation: A single cut is made on the whole stick, so it costs 7.

Example 3

Input: n = 1000000000 cuts = [125000000, 250000000, 375000000, 500000000, 625000000, 750000000, 875000000]

Output: 3000000000

Explanation: Cut at the middle, then at the middles of the two halves, then at the middles of the four quarters. Each round costs 109 in all, so the total is 3 × 109.

Check your understanding

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

n = 12, cuts = [4, 7, 6]

Constraints

  • 2 ≤ n ≤ 109
  • 1 ≤ cuts.length ≤ min(n − 1, 500)
  • 1 ≤ cuts[i] ≤ n − 1
  • All the values in cuts are distinct.

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.