Data Structures & AlgorithmsHardCodeforces Div2 C/D · Amazon SDE OA

A rod of length 8 can be cut into integer pieces, and a piece of length L sells for p[L] with p = [1, 5, 8, 9, 10, 17, 17, 20] for L = 1..8. Find the maximum total revenue by DP over the first piece cut.

A rod of length 8 can be cut into integer pieces, and a piece of length L sells for p[L] with p = [1, 5, 8, 9, 10, 17, 17, 20] for L = 1..8. Find the maximum total revenue by DP over the first piece cut.
p=[0,1,5,8,9,10,17,17,20]
n=8
best=[0]*(n+1)
for x in range(1,n+1):
    best[x]=max([p[l]+best[x-l] for l in range(1,x+1)])
print(best[n])
What is printed?
  1. A. 20
  2. B. 21
  3. C. 22
  4. D. 18

Correct answer: C. 22

Rod cutting DP: the best value for length x is the max over the first piece length l of p[l] plus the best for the rest. Restricting pieces to length four or less loses the 8-long combinations, taking only the single best price ignores combinations, and excluding the full-length piece drops the option of not cutting.

More Coding Interview Problems questions

Exams that ask this topic