RodCutting DP
RodCutting DP
Length 1 2 3 4 5 6 7 8 9 10
Price 1 5 8 9 10 17 17 20 24 30
Given a rod of length n, how to break it and sell for maximum price?
The rod cutting problem
Length 1 2 3 4 5 6 7 8 9 10
Price 1 5 8 9 10 17 17 20 24 30
Eg: n=8
No cut: 20
1+7:18
2+3+3: 21
Optima: 2+6: 22
Rod Cutting
Problem:
Input: n and P(1), P(2), …, P(n)
P(i): price of selling a piece of length i
Output:
(n1,n2,…,nk): n1+n2+ … +nk = n
And P(n1)+P(n2)+…+P(nk) is maximized.
Dynamic Programming
Step 1: Identify subproblems to be solved.
For i=1 to n:
R(i)=Maximum price that can be obtained by breaking
and selling a piece of length i.
Step 2: Recurrence
Set i=n
While (J(i)<i) do:
print(J(i))
Set i=i-J(i)
Print i
Example run for n=10:
i 1 2 3 4 5 6 7 8 9 10
P(i) 1 5 8 9 10 17 17 20 24 30
R(i) 1 5 8 10 13 17 18 22 25 30
J(i) 1 2 3 1 2 6 1 2 3 10
Example for n=15: