The Maximum Product Cutting problem can be defined as follows: Given a rope of length n, what is the maximum product of lengths obtained by cutting the rope i.e. if the rope is cut into r pieces, then find the maximum product of lengths of r pieces.
The dynamic programming approach to this problem involves breaking down the problem into sub-problems and storing their solutions in a table, so that they can be referenced later when solving larger problems.
Let’s define an array ‘dp‘, where ‘dp[i]‘ represents the maximum product that can be obtained from a rope of length ‘i‘. We will populate this array iteratively.
Our base cases are:
- ‘dp[0] = 0‘
- ‘dp[1] = 0‘
For a rope of length ‘i‘, we iterate from ‘j = 1‘ to ‘j = i - 1‘, keeping track of the maximum product that can be obtained by cutting the rope at different positions. For each ‘j‘, we calculate the current product as ‘j * (i - j)‘ and add it to the maximum product that can be obtained from the remaining rope (‘dp[i - j]‘).
The maximum of these products for different ‘j‘ is stored in ‘dp[i]‘. This can be expressed as follows:
for(int i = 2; i <= n; i++){
for(int j = 1; j < i; j++){
dp[i] = Math.max(dp[i], j * (i - j) * dp[i - j]);
}
}
Once the loop is complete, ‘dp[n]‘ will contain the maximum product that can be obtained from the rope of length ‘n‘.
Here’s the complete Java code for the solution:
public static int maxProductCut(int n) {
int[] dp = new int[n + 1];
dp[0] = 0;
dp[1] = 0;
for(int i = 2; i <= n; i++){
for(int j = 1; j < i; j++){
dp[i] = Math.max(dp[i], j * (i - j) * dp[i - j]);
}
}
return dp[n];
}
Let’s run a few test cases to verify our solution:
Input: n = 5
Output: 6
Explanation:
- Cut at 2, the product is maximum 2*3=6
- Cut at 3, the product is maximum 1*2*2=4
- Cut at 4, the product is maximum 3*1=3
Therefore, the maximum product is 6.
Input: n = 10
Output: 36
Explanation:
- Cut at 2, the product is maximum 2*8=16
- Cut at 3, the product is maximum 3*7=21
- Cut at 4, the product is maximum 4*6=24
- Cut at 5, the product is maximum 5*5=25
- Cut at 6, the product is maximum 3*3*4=36
- Cut at 7, the product is maximum 6*1*3=18
- Cut at 8, the product is maximum 2*6=12
Therefore, the maximum product is 36.