...
/Solution Review: The Rod Cutting Problem
Solution Review: The Rod Cutting Problem
In this lesson, we will look at different algorithms to solve the rod cutting problem we saw in the last lesson.
Solution 1: Simple recursion #
def rodCutting(n, prices):if n<0:return 0max_val = 0for i in range(1,n+1):max_val = max(max_val, prices[i-1] + rodCutting(n - i, prices))return max_valprint(rodCutting(3, [3,7,8]))
Explanation
The idea of this algorithm is to exhaustively find the most optimal cuts from every combination of cuts. We do this by making recursive calls with all possible values of length and choosing those that give us the highest revenue (lines 5-7).
The crux of this algorithm is in line 6. We make recursive calls for each possible length of the piece (i
); the updated value of n
now is i
units smaller. Once this result is evaluated, we add this length’s price and find the max
.
The visualization below shows a dry run of this algorithm.
Time complexity
Can you think of the number of combinations of cuts for a rod of length n? It is ...