Given that selling a rod of length i yields a profit of pi , how do we cut a rod of length n to maximize the total revenue?
Method 1: Recursion
The most straightforward approach is to solve it using recursion. As shown in the figure below, rn represents the maximum revenue obtainable by cutting a rod of length n. Suppose i is the length of the first segment in the optimal solution; then rn = pi + rn−i, because pi is the revenue from the first segment in the optimal solution, and adding the maximum revenue from the remaining part gives us the answer.
How do we find i? By looping through i from 0 to n−1, evaluating each combination pi + rn−i, and selecting the maximum value as the answer.
However, this approach has a problem: each time we compute rn−i, it requires recursively calculating its optimal solution, leading to repeated calculations. For instance, when computing r4, we need to compute r3, r2, r1, r0, and computing r3 requires recomputing r2, r1, r0. Therefore, we can use Dynamic Programming (DP) to save time.
Method 2: DP
We can build a table to store the values of each ri, so we don’t have to recalculate them every time i is needed.
Given r0 and r1, we can compute r2 as follows: r2 = max( p1 + r1, p2 + r0 ). Next, using r1 and r2, we can compute r3, and finally determine r5. The most crucial part is still the recursive formula pi + rn-i.
Quick Note
Building a table to store repetitive parts in recursion is a key technique in Dynamic Programming!