DP #13. Rod Cutting Problem. - mbhushan/dynpro GitHub Wiki

(13). Rod Cutting Problem.

Given a rod of length n inches and an array of prices that contains prices of 
all pieces of size smaller than n. Determine the maximum value obtainable by 
cutting up the rod and selling the pieces. For example, if length of the rod 
is 8 and the values of different pieces are given as following, then the maximum 
obtainable value is 22 (by cutting in two pieces of lengths 2 and 6)


length   | 1   2   3   4   5   6   7   8  
--------------------------------------------
price    | 1   5   8   9  10  17  17  20

And if the prices are as following, then the maximum obtainable value is 24 
(by cutting in eight pieces of length 1)

length   | 1   2   3   4   5   6   7   8  
--------------------------------------------
price    | 3   5   8   9  10  17  17  20
Formula:
j <- rod length
len(i) <- rod of len i
val(i) <- value of rod of len i

if (j >= i) {
    T[i][j] = Max (
                    T[i-1][j], T[i][j-len(i)] + val(i);
                  )
} else {
    T[i][j] = T[i-1][j];
}
Example:
len [] = {1, 2, 3, 4};
prices [] = {2, 5, 7, 8};

target len = 5;
len(price) 0 1 2 3 4 5
1 (2) 0 2 4 6 8 10
2 (5) 0 2 5 7 10 12
3 (7) 0 2 5 7 10 12
4 (8) 0 2 5 7 10 12 <- max profit

Rod Cutting - Max Profit

  • Time Complexity: O(len * size(rods))
  • Space Complexity: O(len * size(rods))