Minimum Cost to Cut a Stick - Problem

Given a wooden stick of length n units. The stick is labelled from 0 to n. For example, a stick of length 6 is labelled as follows:

[0] --- [1] --- [2] --- [3] --- [4] --- [5] --- [6]

Given an integer array cuts where cuts[i] denotes a position you should perform a cut at.

You should perform the cuts in order, you can change the order of the cuts as you wish.

The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut).

Return the minimum total cost of the cuts.

Input & Output

Example 1 — Basic Case
$ Input: n = 7, cuts = [1,3,4,5]
Output: 16
💡 Note: One optimal order: cut at 5 (cost=7), then cut at 3 (cost=5), then cut at 4 (cost=2), then cut at 1 (cost=3). Total: 7+5+2+3=17. Better order exists with cost 16.
Example 2 — Single Cut
$ Input: n = 9, cuts = [5]
Output: 9
💡 Note: Only one cut at position 5, so the cost is the length of the entire stick: 9.
Example 3 — Two Cuts
$ Input: n = 6, cuts = [2,4]
Output: 10
💡 Note: Cut at 2 first (cost=6), then cut at 4 in right piece [2,6] (cost=4). Total: 6+4=10. Or cut at 4 first (cost=6), then at 2 in left piece [0,4] (cost=4). Total: 6+4=10. Both orders give the same minimum cost of 10.

Constraints

  • 2 ≤ n ≤ 106
  • 1 ≤ cuts.length ≤ min(n - 1, 100)
  • 1 ≤ cuts[i] ≤ n - 1
  • All the integers in cuts array are distinct.

Visualization

Tap to expand
Minimum Cost to Cut a Stick INPUT Wooden Stick (n = 7) 0 1 2 3 4 5 6 7 Input Values: n = 7 cuts = [1, 3, 4, 5] Cuts Array: 1 3 4 5 Extended: [0,1,3,4,5,7] (with boundaries) ALGORITHM STEPS 1 Extend cuts array Add 0 and n as boundaries 2 Sort extended array [0,1,3,4,5,7] sorted 3 Build DP table dp[i][j] = min cost for [i,j] 4 Try all cut orders Find optimal sequence DP Transition: dp[i][j] = min( dp[i][k] + dp[k][j] + cost ) for all k in (i,j) Optimal Cut Order: Cut at 3: cost=7 (0 to 7) Cut at 5: cost=4 (3 to 7) Cut at 1: cost=3, Cut at 4: cost=2 Total: 7+4+3+2 = 16 FINAL RESULT Optimal Cutting Sequence: 0 7 1. 0 3 7 2. cost:7 3. 5 cost:4 4. 1 c:3 5. 4 c:2 Cost: 7 + 4 + 3 + 2 = 16 Output: 16 OK - Minimum cost achieved Key Insight: The order of cuts matters! Use interval DP where dp[i][j] represents the minimum cost to make all cuts between position i and j. For each subproblem, try every possible first cut and take the minimum. Time: O(n^3), Space: O(n^2) where n = number of cuts + 2 (boundaries). TutorialsPoint - Minimum Cost to Cut a Stick | DP Approach
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
125.0K Views
Medium Frequency
~35 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen