Maximize The Cut Segments
Pattern: 1D DP
Cut a rod of length n into pieces of lengths x, y or z, maximising the number of pieces; leftovers are not allowed. best(m) = 1 + the best of best(m - x), best(m - y), best(m - z), using only reachable lengths.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Cut a segment of length n into pieces of lengths x, y or z (any number of each) with nothing left over, making as
many pieces as possible. Return that number, or 0 if it cannot be done. n = 4, x = 2, y = 1, z = 1 gives 4. The catalogue has no practice link for this one.
Think first
- What was the last piece cut?
- When is a length impossible?
- Why not greedy with the shortest piece?
Hints
Brute force, and why it fails
Try every sequence of cuts: exponential.
The key insight
Like coin change, but counting pieces and maximising.
Dry run
| best | 0 1 2 |
|---|
n = 4, cuts 2, 1, 1. best(1) = 1, best(2) = 2.
The plan
best[0] = 0; others -1
for m: for c in x, y, z: if c <= m and best[m - c] != -1: best[m] = max(best[m], best[m - c] + 1)
Complexity
- Time
O(n)- Space
O(n)
Three choices per length.
Edge cases
- Impossible: 0.
- One piece equals n: at least 1.
- Equal cut lengths.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int maximizeTheCuts(int n, int x, int y, int z) {
int[] best = new int[n + 1]; // best[m]: most pieces for length m, or -1 if impossible
Arrays.fill(best, -1);
best[0] = 0;
for (int m = 1; m <= n; m++)
for (int c : new int[]{x, y, z})
if (c <= m && best[m - c] != -1) best[m] = Math.max(best[m], best[m - c] + 1); // the last piece has length c
return Math.max(best[n], 0); // 0 when no exact cutting exists
}
}C++
class Solution {
public:
int maximizeTheCuts(int n, int x, int y, int z) {
vector<int> best(n + 1, -1); // best[m]: most pieces for length m, or -1 if impossible
best[0] = 0;
int cuts[3] = {x, y, z};
for (int m = 1; m <= n; m++)
for (int c : cuts)
if (c <= m && best[m - c] != -1) best[m] = max(best[m], best[m - c] + 1); // the last piece has length c
return max(best[n], 0); // 0 when no exact cutting exists
}
};Python
class Solution:
def maximizeTheCuts(self, n: int, x: int, y: int, z: int) -> int:
best = [0] + [-1] * n # best[m]: most pieces for length m, or -1 if impossible
for m in range(1, n + 1):
for c in (x, y, z):
if c <= m and best[m - c] != -1:
best[m] = max(best[m], best[m - c] + 1) # the last piece has length c
return max(best[n], 0) # 0 when no exact cutting existsCommon mistakes
- Allowing leftovers.
- Treating -1 as a valid count.