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
A naive solution for this problem is to generate all configurations of different pieces and find the highest priced configuration. This solution is exponential in term of time complexity.
Here we will use memoization by storing all calculated values in a variable called temp_val. Following is the Python code for getting the maximum value after cutting the rod.
def cut_rod(price,size):
temp_val = [0 for i in range(size+1)]
for length in range(1,size+1):
maximum = -999
for splits in range(length):
maximum = max(maximum, price[splits] + temp_val[length-splits-1])
temp_val[length] = maximum
return temp_val[size]
price = [1,5,8,9,10,17,17,20]
ans = cut_rod(price, len(price))
print(ans)
Time Complexity: $$O(n^2)$$