Given a rod of length n inches and an array of prices that includes prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if the length of the rod is 8 and the values of different pieces are given as the following, then the maximum obtainable value is 22 (by cutting in two pieces of lengths 2 and 6)
Method 1: A naive solution to this problem is to generate all configurations of different pieces and find the highest-priced configuration. This solution is exponential in terms of time complexity. Let us see how this problem possesses both important properties of a Dynamic Programming (DP) Problem and can efficiently be solved using Dynamic Programming.
1) Optimal Substructure:
We can get the best price by making a cut at different positions and comparing the values obtained after a cut. We can recursively call the same function for a piece obtained after a cut. Let cutRod(n) be the required (best possible price) value for a rod of length n. cutRod(n) can be written as follows. cutRod(n) = max(price[i] + cutRod(n-i-1)) for all i in {0, 1 .. n-1}
C++
// A recursive solution for Rod cutting problem
#include <bits/stdc++.h>
#include <iostream>
#include <math.h>
usingnamespacestd;
// A utility function to get the maximum of two integers
intmax(inta, intb) { return(a > b) ? a : b; }
/* Returns the best obtainable price for a rod of length n
and price[] as prices of different pieces */
intcutRod(intprice[], intindex, intn)
{
// base case
if(index == 0) {
returnn * price[0];
}
//At any index we have 2 options either
//cut the rod of this length or not cut
//it
intnotCut = cutRod(price,index - 1,n);
intcut = INT_MIN;
introd_length = index + 1;
if(rod_length <= n)
cut = price[index]
+ cutRod(price,index,n - rod_length);
returnmax(notCut, cut);
}
/* Driver program to test above functions */
intmain()
{
intarr[] = { 1, 5, 8, 9, 10, 17, 17, 20 };
intsize = sizeof(arr) / sizeof(arr[0]);
cout << "Maximum Obtainable Value is "
<< cutRod(arr, size - 1, size);
getchar();
return0;
}
//This code is contributed by Sanskar
Java
// Java recursive solution for Rod cutting problem
importjava.io.*;
classGFG {
/* Returns the best obtainable price for a rod of length
n and price[] as prices of different pieces */
staticintcutRod(intprice[], intindex, intn)
{
// base case
if(index == 0) {
returnn * price[0];
}
// At any index we have 2 options either
// cut the rod of this length or not cut
// it
intnotCut = cutRod(price, index - 1, n);
intcut = Integer.MIN_VALUE;
introd_length = index + 1;
if(rod_length <= n)
cut = price[index]
+ cutRod(price, index, n - rod_length);
returnMath.max(notCut, cut);
}
/* Driver program to test above functions */
publicstaticvoidmain(String args[])
{
intarr[] = { 1, 5, 8, 9, 10, 17, 17, 20};
intsize = arr.length;
System.out.println("Maximum Obtainable Value is "
+ cutRod(arr, size - 1, size));
}
}
// This code is contributed by Lovely Jain
Python3
# A recursive solution for Rod cutting problem
# Returns the best obtainable price for a rod of length n
print("Maximum Obtainable Value is ",cutRod(arr, size -1, size))
# This code is contributed by Vivek Maddeshiya
C#
// C# recursive solution for Rod cutting problem
usingSystem;
publicclassGFG {
staticintmax(inta, intb) {
if(a > b) returna;
returnb;
}
staticintMIN_VALUE = -1000000000;
/* Returns the best obtainable price for a rod of
// length n and price[] as prices of different pieces */
staticintcutRod(int[] price, intindex, intn) {
// base case
if(index == 0) {
returnn * price[0];
}
// At any index we have 2 options either
// cut the rod of this length or not cut it
intnotCut = cutRod(price, index - 1, n);
intcut = MIN_VALUE;
introd_length = index + 1;
if(rod_length <= n)
cut = price[index] + cutRod(price, index, n - rod_length);
returnmax(notCut, cut);
}
// Driver program to test above functions
publicstaticvoidMain(string[] args) {
int[] arr = {1, 5, 8, 9, 10, 17, 17, 20 };
intsize = arr.Length;
Console.WriteLine("Maximum Obtainable Value is "+
cutRod(arr, size - 1, size));
}
}
// This code is contributed by ajaymakavana.
Javascript
// A recursive solution for Rod cutting problem
/* Returns the best obtainable price for a rod of length n
and price[] as prices of different pieces */
functioncutRod(price, index, n)
{
// base case
if(index == 0) {
returnn * price[0];
}
//At any index we have 2 options either
//cut the rod of this length or not cut
//it
let notCut = cutRod(price,index - 1,n);
let cut = Number.MIN_VALUE;
let rod_length = index + 1;
if(rod_length <= n)
cut = price[index]
+ cutRod(price,index,n - rod_length);
returnMath.max(notCut, cut);
}
/* Driver program to test above functions */
let arr = [ 1, 5, 8, 9, 10, 17, 17, 20 ];
let size = arr.length;
console.log("Maximum Obtainable Value is "
+ cutRod(arr, size - 1, size));
// This code is contributed by garg28harsh.
Output
Maximum Obtainable Value is 22
Time Complexity: O(2n) where n is the length of the price array.
Space Complexity: O(n) where n is the length of the price array.
2) Overlapping Subproblems:
The following is a simple recursive implementation of the Rod Cutting problem. The implementation simply follows the recursive structure mentioned above.
C++
// A memoization solution for Rod cutting problem
#include <bits/stdc++.h>
#include <iostream>
#include <math.h>
usingnamespacestd;
// A utility function to get the maximum of two integers
intmax(inta, intb) { return(a > b) ? a : b; }
/* Returns the best obtainable price for a rod of length n
and price[] as prices of different pieces */
intcutRod(intprice[], intindex, intn,
vector<vector<int> >& dp)
{
// base case
if(index == 0) {
returnn * price[0];
}
if(dp[index][n] != -1)
returndp[index][n];
// At any index we have 2 options either
// cut the rod of this length or not cut
// it
intnotCut = cutRod(price, index - 1, n,dp);
intcut = INT_MIN;
introd_length = index + 1;
if(rod_length <= n)
cut = price[index]
+ cutRod(price, index, n - rod_length,dp);
returndp[index][n]=max(notCut, cut);
}
/* Driver program to test above functions */
intmain()
{
intarr[] = { 1, 5, 8, 9, 10, 17, 17, 20 };
intsize = sizeof(arr) / sizeof(arr[0]);
vector<vector<int> > dp(size,
vector<int>(size + 1, -1));
cout << "Maximum Obtainable Value is "
<< cutRod(arr, size - 1, size, dp);
getchar();
return0;
}
// This code is contributed by Sanskar
Java
// A memoization solution for Rod cutting problem
importjava.io.*;
importjava.util.*;
/* Returns the best obtainable price for a rod of length n
In the above partial recursion tree, cR(2) is solved twice. We can see that there are many subproblems that are solved again and again. Since the same subproblems are called again, this problem has the Overlapping Subproblems property. So the Rod Cutting problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of the same subproblems can be avoided by constructing a temporary array val[] in a bottom-up manner.
C++
// A Dynamic Programming solution for Rod cutting problem
#include<iostream>
#include <bits/stdc++.h>
#include<math.h>
usingnamespacestd;
// A utility function to get the maximum of two integers
intmax(inta, intb) { return(a > b)? a : b;}
/* Returns the best obtainable price for a rod of length n and
price[] as prices of different pieces */
intcutRod(intprice[], intn)
{
intval[n+1];
val[0] = 0;
inti, j;
// Build the table val[] in bottom up manner and return the last entry
// from the table
for(i = 1; i<=n; i++)
{
intmax_val = INT_MIN;
for(j = 0; j < i; j++)
max_val = max(max_val, price[j] + val[i-j-1]);
val[i] = max_val;
}
returnval[n];
}
/* Driver program to test above functions */
intmain()
{
intarr[] = {1, 5, 8, 9, 10, 17, 17, 20};
intsize = sizeof(arr)/sizeof(arr[0]);
cout <<"Maximum Obtainable Value is "<<cutRod(arr, size);
getchar();
return0;
}
// This code is contributed by shivanisinghss2110
C
// A Dynamic Programming solution for Rod cutting problem
#include<stdio.h>
#include<limits.h>
// A utility function to get the maximum of two integers
intmax(inta, intb) { return(a > b)? a : b;}
/* Returns the best obtainable price for a rod of length n and
price[] as prices of different pieces */
intcutRod(intprice[], intn)
{
intval[n+1];
val[0] = 0;
inti, j;
// Build the table val[] in bottom up manner and return the last entry
// from the table
for(i = 1; i<=n; i++)
{
intmax_val = INT_MIN;
for(j = 0; j < i; j++)
max_val = max(max_val, price[j] + val[i-j-1]);
val[i] = max_val;
}
returnval[n];
}
/* Driver program to test above functions */
intmain()
{
intarr[] = {1, 5, 8, 9, 10, 17, 17, 20};
intsize = sizeof(arr)/sizeof(arr[0]);
printf("Maximum Obtainable Value is %d", cutRod(arr, size));
getchar();
return0;
}
Java
// A Dynamic Programming solution for Rod cutting problem
importjava.io.*;
classRodCutting
{
/* Returns the best obtainable price for a rod of
length n and price[] as prices of different pieces */
staticintcutRod(intprice[],intn)
{
intval[] = newint[n+1];
val[0] = 0;
// Build the table val[] in bottom up manner and return
// the last entry from the table
for(inti = 1; i<=n; i++)
{
intmax_val = Integer.MIN_VALUE;
for(intj = 0; j < i; j++)
max_val = Math.max(max_val,
price[j] + val[i-j-1]);
val[i] = max_val;
}
returnval[n];
}
/* Driver program to test above functions */
publicstaticvoidmain(String args[])
{
intarr[] = newint[] {1, 5, 8, 9, 10, 17, 17, 20};
intsize = arr.length;
System.out.println("Maximum Obtainable Value is "+
cutRod(arr, size));
}
}
/* This code is contributed by Rajat Mishra */
Python3
# A Dynamic Programming solution for Rod cutting problem
INT_MIN =-32767
# Returns the best obtainable price for a rod of length n and
# price[] as prices of different pieces
defcutRod(price, n):
val =[0forx inrange(n+1)]
val[0] =0
# Build the table val[] in bottom up manner and return
# the last entry from the table
fori inrange(1, n+1):
max_val =INT_MIN
forj inrange(i):
max_val =max(max_val, price[j] +val[i-j-1])
val[i] =max_val
returnval[n]
# Driver program to test above functions
arr =[1, 5, 8, 9, 10, 17, 17, 20]
size =len(arr)
print("Maximum Obtainable Value is "+str(cutRod(arr, size)))
document.write("Maximum Obtainable Value is "+ cutRod(arr, size) + "n");
</script>
Output
Maximum Obtainable Value is 22
The Time Complexity of the above implementation is O(n^2), which is much better than the worst-case time complexity of Naive Recursive implementation.
Space Complexity: O(n) as val array has been created.
3) Using the idea of Unbounded Knapsack.
This problem is very similar to the Unbounded Knapsack Problem, where there are multiple occurrences of the same item. Here the pieces of the rod. Now I will create an analogy between Unbounded Knapsack and the Rod Cutting Problem.
We will divide the problem into smaller sub-problems. Then using a 2-D matrix, we will calculate the maximum price we can achieve for any particular weight
console.log("Maximum obtained value is "+ cutRod(prices, n));
Output
Maximum obtained value is 22
Time Complexity: O(n2) Auxiliary Space: O(n2)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!