Minimum Cost to Cut a Stick

Implement minCost

A wooden stick of length `n` needs a cut made at every position listed in `cuts`. Making a cut costs the length of whichever piece it's currently slicing, and once a piece is cut it splits into two independent pieces that each keep needing their own remaining cuts. The order the cuts happen in changes the total cost, because an early cut on a long, still-uncut stick is expensive, while the same cut made later — after the stick around it has already been chopped down — is cheap. Find the order that minimizes the total. The trick is to stop thinking about cut *order* and instead think about cut *positions*. Sort every requested cut position together with the two ends of the stick (0 and n) into one list of boundary points. Any stretch of stick between two of those points, once every point strictly inside it has been cut, never needs to be touched again — so the cheapest way to finish that stretch depends only on its two endpoints, not on how it was reached. That cost is the stretch's current length (paid once, by whichever cut happens last inside it) plus the cost of finishing whatever's left on each side of that final cut — and trying every possible "last cut" position finds the cheapest one.

Example 1:

Input: n = 8, cuts = [1,7]

Output: 15

Example 2:

Input: n = 1, cuts = []

Output: 0

Example 3:

Input: n = 10, cuts = [5]

Output: 10

+ 6 hidden test cases run on Submit.

Constraints:

  • 1 ≤ n ≤ 30
  • 0 ≤ cuts.length ≤ 6
  • 1 ≤ cuts[i] < n, all cuts distinct

n =

8

cuts =

[1, 7]