Minimum Cost to Cut a Stick (LeetCode 1547): Solution and Explanation
A stick of length n must be cut at every position in cuts. Each cut costs the length of the piece it is made on, and you can choose the order. Find the order with the smallest total cost.
Intuition
The order matters because a cut made early lands on a long piece and costs a lot, while the same cut made later lands on a short piece. Trying every order is factorial in the number of cuts, so we need a way to share work between orders.
Look at the very first cut made on some piece. It costs the full length of that piece, whichever cut it is. After it, the left part and the right part never interact again: cuts on one side cannot change the length of a piece on the other side. So the best cost for a piece is its length plus the best cost of its two halves, minimised over which cut goes first.
Every piece that can ever appear runs from one cut point (or a stick end) to another. Sorting the cuts and adding 0 and n gives a list of m points, and a piece is just a pair of indices (i, j) into it. That turns the problem into an interval DP over at most about 100 points.
Pieces with no cut inside cost nothing. Filling the table by increasing gap j - i guarantees both halves of every split are already known when a wider piece is priced.
Approach: Interval DP over sorted cut points
- Build
c = [0] + sorted(cuts) + [n]and letm = len(c). - Let
dp[i][j]be the minimum cost of making every cut strictly betweenc[i]andc[j]. Neighbouring points havedp[i][i+1] = 0. - For each gap
lengthfrom 2 to m - 1, and each starti, setj = i + length. - Try every
kwithi < k < jas the first cut:dp[i][k] + dp[k][j]. Take the minimum and add the piece lengthc[j] - c[i]. - Return
dp[0][m-1], the cost for the whole stick.
Step-by-step example
n = 7, cuts = [1,3,4,5]
- Points are c = [0, 1, 3, 4, 5, 7]. All gaps of one step cost 0.
- Gap 2: [0,3] costs 3, [1,4] costs 3, [3,5] costs 2, [4,7] costs 3. Each has exactly one cut inside, so the cost is just the piece length.
- Gap 3: [0,4] = 4 + min(0+3, 3+0) = 7, [1,5] = 4 + min(0+2, 3+0) = 6, [3,7] = 4 + min(0+3, 2+0) = 6.
- Gap 4: [0,5] = 5 + min(0+6, 3+2, 7+0) = 10, [1,7] = 6 + min(0+6, 3+3, 6+0) = 12.
- Gap 5: [0,7] = 7 + min(0+12, 3+6, 7+3, 10+0) = 7 + 9 = 16, with the first cut at position 3.
- Replaying the choices: cut at 3 (cost 7), then 1 on [0,3] (3) and 5 on [3,7] (4), then 4 on [3,5] (2). Total 16.
Code: Python, Java, C++
1class Solution:
2 def minCost(self, n: int, cuts: List[int]) -> int:
3 c = [0] + sorted(cuts) + [n]
4 m = len(c)
5 dp = [[0] * m for _ in range(m)]
6 for length in range(2, m):
7 for i in range(m - length):
8 j = i + length
9 best = float('inf')
10 for k in range(i + 1, j):
11 best = min(best, dp[i][k] + dp[k][j])
12 dp[i][j] = best + c[j] - c[i]
13 return dp[0][m - 1]1class Solution {
2 public int minCost(int n, int[] cuts) {
3 int m = cuts.length + 2;
4 int[] c = new int[m];
5 Arrays.sort(cuts);
6 for (int i = 0; i < cuts.length; i++) c[i + 1] = cuts[i];
7 c[m - 1] = n;
8 int[][] dp = new int[m][m];
9 for (int len = 2; len < m; len++) {
10 for (int i = 0; i + len < m; i++) {
11 int j = i + len;
12 int best = Integer.MAX_VALUE;
13 for (int k = i + 1; k < j; k++) {
14 best = Math.min(best, dp[i][k] + dp[k][j]);
15 }
16 dp[i][j] = best + c[j] - c[i];
17 }
18 }
19 return dp[0][m - 1];
20 }
21}1class Solution {
2public:
3 int minCost(int n, vector<int>& cuts) {
4 vector<int> c(cuts.begin(), cuts.end());
5 c.push_back(0);
6 c.push_back(n);
7 sort(c.begin(), c.end());
8 int m = c.size();
9 vector<vector<int>> dp(m, vector<int>(m, 0));
10 for (int len = 2; len < m; len++) {
11 for (int i = 0; i + len < m; i++) {
12 int j = i + len;
13 int best = INT_MAX;
14 for (int k = i + 1; k < j; k++) {
15 best = min(best, dp[i][k] + dp[k][j]);
16 }
17 dp[i][j] = best + c[j] - c[i];
18 }
19 }
20 return dp[0][m - 1];
21 }
22};Time and space complexity
O(m^3)
There are O(m^2) pieces and each tries up to m first cuts, where m is the number of cuts plus 2. With at most 100 cuts that is about a million steps.
O(m^2)
The table stores one value for every pair of points.
Other approaches
Top-down memoised recursion (time O(m^3), space O(m^2))
Write cost(i, j) recursively with the same recurrence and cache results in a dictionary or 2D array. It does the same work as the table and is often easier to write in an interview.
Try every order (time O(c! * c), space O(c))
Simulate all permutations of the cuts and keep the cheapest. It is correct but grows factorially, so it only works for a handful of cuts and is useful as a brute-force checker.
Common mistakes
- Indexing the DP by stick positions instead of by cut indices. With n up to a million a position-based table is far too large.
- Forgetting to sort the cuts. The interval recurrence only works when points are in order along the stick.
- Leaving out the 0 and n end points, which makes the cost of the first cut on the whole stick impossible to express.
- Filling the table row by row from the top instead of by increasing gap, so a split reads a half that has not been computed yet.
Frequently asked questions
Why does the first cut on a piece cost the whole piece length regardless of which cut it is?
Before the first cut, the piece is intact, so any cut made on it costs its full length. Only the cuts after it see shorter pieces, which is why the choice of first cut matters for the rest of the cost.
How is this related to Burst Balloons?
Both are interval DP problems where you pick one element inside a range and the range splits into two independent subproblems. Burst Balloons picks the last balloon to burst, this problem picks the first cut to make.
Can the cost overflow a 32-bit integer?
No. Every cut costs at most n, and each position along the stick is charged at most once per cut level, so the total stays far below 2^31 for n up to a million and 100 cuts.
What is the time complexity of the interval DP?
O(m^3) time and O(m^2) space, where m is the number of cuts plus 2. The stick length n does not appear, because only cut positions matter.