Rod Cutting Educative
Rod Cutting Educative
Rod Cutting Educative
Dynamic Programming in
Python: Optimizing Programs
for Efficiency
0% completed
Search Course
Chapter 1: From
Recursion to Dynamic
Programming
Introduction
What is Recursion?
Thinking Recursively
Approaches of Dynamic
Programming
Quiz
Chapter 2: Top-Down
Dynamic Programming
with Memoization
What is Memoization?
Quiz
Chapter 3: Bottom-Up
Ask a Question
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.
5 of 15
Time complexity
Can you think of the number of combinations of cuts for a rod of length
n? It is 2n−1 ! For a rod of length n, at each position, we have two choices.
Either we can make a cut, or we can leave it as it is. All combinations are
bounded by O(2^n) as is the time complexity of this solution.
Optimal substructure
We want to find the optimal answer for a rod of length n, and we have
optimal answers to all the subproblems, i.e., rods of length n-1, n-2, … , 2,
1. We can find the maximum of all the subproblem’s results plus the
price of the rod length that remains along with that subproblem. The
following would be the equation for finding the optimal cut’s revenue
for a rod of length n.
Overlapping subproblems
By looking at the visualization above, you can already see one
overlapping subproblem. For bigger inputs, this overlap will increase
substantially.
substantially.
Ask a Question
revenue = 8
revenue = 10 revenue = 10
r=3r=3 r=3
revenue = 9
1 of 3
This calls for the memoization of results! Let’s look at the top-down
implementation of this algorithm.
Explanation
You have seen this many times now: there’s nothing fancy here! Before
evaluating a result, we check if it is already computed and available in
the memo (lines 4-5); in this case, we do not need to evaluate it. If we have
to evaluate it, we simply store results in the memo for future reuse (line 9).
Explanation
The idea is to start building from the case of a rod of length 1, and then
use these results to solve the problems for bigger lengths. The solution to
a problem of the rod of length n would not require answers to the
problems of rods greater in length than n. Therefore, the for loop at line
eight only iterates until i, which is any given length of the rod up to n.
We make every possible cut, and for the remaining rod length, we would
already have the solution in dp. Thus, we choose the cut that gives the
highest possible answers (line 10).
Back Next
Mark as Completed
Report an Issue