Minimum Cost to Cut a Stick

A wooden stick of length n is marked at positions 0 to n. The array cuts lists the positions where you must cut. You may perform the cuts in any order. Each cut costs the length of the stick piece being cut, and splits it into two smaller pieces. Return the minimum total cost of performing all the cuts.

30:00

Minimum Cost to Cut a Stick
hard
Free written solution
Topics
Companies

A wooden stick of length n is marked at positions 0 to n. The array cuts lists the positions where you must cut. You may perform the cuts in any order. Each cut costs the length of the stick piece being cut, and splits it into two smaller pieces. Return the minimum total cost of performing all the cuts.

Example 1:
Input: {"n":7,"cuts":[1,3,4,5]}
Output: 16
Constraints:
  • 2≤n≤1062 \leq n \leq 10^6

  • 1≤cuts.length≤min⁡(n−1,100)1 \leq \text{cuts.length} \leq \min(n - 1, 100)

  • 1≤cuts[i]≤n−11 \leq \text{cuts}[i] \leq n - 1

  • All the integers in cuts are distinct.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":7,"cuts":[1,3,4,5]}

Sort the cuts and add the two stick ends: points = [0, 1, 3, 4, 5, 7]. dp[i][j] will be the cheapest way to make every cut strictly between points[i] and points[j].

stick (points spaced evenly, labels are real positions)

0p01p13p24p35p47p5

dp[i][j] = min cost for all cuts between p_i and p_j

0
1
2
3
4
5
0
0
1
0
2
0
3
0
4
0
5

▢ piece being priced

| trial cut

■ left part

■ right part

Variables
VariableValue
m6
i-
j-
k-
DepthFunction Call
Stack empty
0/35