Zonvolt Inc. is a firm that specializes in cutting. They received a batch of long steel rods. Now, they have to cut them into smaller pieces and sell them. Suppose each cut is free, how should they cut in order to maximize their profit?
Question ()
Given a rob of length n and a price table, determine the maximum possible revenue.
1. Define optimal subproblems
rev(n) = max revenue for rod of length n
2. Recurrence - solve by suffix
rev(n) = max(price[i] + rev(n-i)) for i from 1 to n
3. Topo order
4. Init base cases
5. Final answer
Brute Force Approach
We can do a dfs to decompose n=4 and find all possible ways to cut
At each unit, we decide whether to cut or not to cut. In total, there are 2n−1 possible ways of cutting.
Top-down Code
func rod(price, n)
// base case
if (n == 0) return 0
// recurrence
rev = MIN_VALUE
for i from 1 to n
rev = max(rev, rod(price[i] + rod(price, n-i)))
end for
// final answer
return rev
end func
The recurrence for this function is T(n)=j=0∑n−1T(j)+O(1).
Runtime Analysis
Theorem: For any n∈N,T(n)=2n.
Proof: Base case n=0:T(0)=1 Inductive hypothesis: Assume T(n−1)=2n−1 Inductive step: T(n)=j=0∑n−1T(j)+1=j=0∑n−2T(j)+T(n−1)+1=T(n−1)−1+T(n−1)+1=2T(n−1) by I.H.=2n
Top-down + Memoization
Conclusion
"My conjecture is that you actually know more computer science than you think." - David Malan
When I was writing the brute force approach, my brain automatically avoided writing the repetitive cuts. But the program procedure doesn't know. So we gonna program it.