Given a rod of length n, find the optimal way to cut the rod into smaller rods to maximize the product of each of the smaller rod’s price. Assume that each rod of length i has price i.

For example, consider the following rod of length 4:

 
Best: Cut the rod into two pieces of length 2 each to gain revenue of 2×2 = 4
 
Cut            Profit
4                4
1, 3            (1 × 3) = 3
2, 2            (2 × 2) = 4
3, 1            (3 × 1) = 3
1, 1, 2         (1 × 1 × 2) = 2
1, 2, 1         (1 × 2 × 1) = 2
2, 1, 1         (2 × 1 × 1) = 2
1, 1, 1, 1      (1 × 1 × 1 × 1) = 1
 
 
Similarly, for n = 6, (3 × 3) = 9
For n = 8, (2 × 3 × 3) = 18
For n = 15, (3 × 3 × 3 × 3 × 3) = 243

Practice this problem

The idea is simple. First, partition the given rod of length n into two parts of length i and n-i for each 1 <= i <= n. Then recur for the rod of length n-i but don’t divide rod of length i any further. Finally, take a maximum of all values. This yields the following recursive relation:

rodcut(n) = max { n, i * rodcut(n – i) } where 1 <= i <= n

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The maximum profit is 243

Java


Download  Run Code

Output:

The maximum profit is 243

Python


Download  Run Code

Output:

The maximum profit is 243

The time complexity of the above solution is O(nn) and occupies space in the call stack, where n is the rod length.
 

 
We have seen that the problem can be broken down into smaller subproblems, which can further be broken down into yet smaller subproblems, and so on. So, the problem has optimal substructure. Let’s consider a recursion tree for the rod of length 4.

Rod cutting problem

As we can see, the same subproblems (highlighted in the same color) are getting computed repeatedly. So, the problem also exhibits overlapping subproblems. We know that problems with optimal substructure and overlapping subproblems can be solved by dynamic programming, where subproblem solutions are memoized rather than computed and again.

We will solve this problem in a bottom-up manner. In the bottom-up approach, we solve smaller subproblems first, then solve larger subproblems from them. The following bottom-up approach computes T[i], which stores the maximum profit achieved from the rod of length i for each 1 <= i <= n. It uses the value of smaller values i already computed.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

The maximum profit is 243

Java


Download  Run Code

Output:

The maximum profit is 243

Python


Download  Run Code

Output:

The maximum profit is 243

The time complexity of the above solution is O(n2) and requires O(n) extra space, where n is the rod length.