Skip to problem
←

Maximize Cut Segments

Medium 0 attempts

You have a rod of length n and three allowed cut lengths x, y, and z. Cut the rod into as many pieces as possible where every piece measures exactly x, y, or z, using up the rod with nothing left over. If there's no way to cut the whole rod into pieces of these lengths, return 0.

Each allowed length may be used any number of times; you do not have to use all three. The lengths may be equal. Count pieces, not the number of cuts: a rod used as one allowed-length piece returns 1.

For n = 7 and lengths 2, 3, 5, choose 2 + 2 + 3 to get three pieces. Repeatedly taking the smallest length alone would leave an unusable remainder.

Function contract

Implement maximizeTheCutSegments(n, x, y, z). Receive the rod length and three allowed positive segment lengths.

Output: Return the maximum number of segments using the entire rod, or 0 if an exact partition is impossible.

Example 1

Input
n = 4
x = 2
y = 1
z = 1
Output
4

Example 2

Input
n = 7
x = 2
y = 4
z = 6
Output
0
Constraints
  • 1 <= n <= 10^4
  • 1 <= x, y, z <= n

Approach: DP (Unbounded Knapsack Variant)

dp[i] stores the maximum number of segments for rod length i. For each length, try cutting with x, y, or z. If the remaining length has a valid solution, update dp[i]. Initialize unreachable lengths to -1, rather than 0, so an impossible remainder cannot create a false solution. The base dp[0] = 0 represents an exactly consumed rod.

javascript
function maximizeTheCutSegments(n, x, y, z) {
  const dp = new Array(n + 1).fill(-1);
  dp[0] = 0;
  for (let i = 1; i <= n; i++) {
    for (const cut of [x, y, z]) {
      if (i >= cut && dp[i - cut] !== -1)
        dp[i] = Math.max(dp[i], dp[i - cut] + 1);
    }
  }
  return Math.max(dp[n], 0);
}

Time Complexity: O(n)

Space Complexity: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript