Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern

What is printed? (rod cutting – maximise revenue)

What is printed? (rod cutting – maximise revenue)
price = [0, 1, 5, 8, 9, 10, 17, 17, 20]
n = 8; r = [0] * (n + 1)
for j in range(1, n + 1):
    r[j] = max(price[i] + r[j - i] for i in range(1, j + 1))
print(r[4], r[8])
  1. A. 9 20
  2. B. 10 20
  3. C. 10 24
  4. D. 10 22

Correct answer: D. 10 22

r[j] = max over the first piece i of price[i] + r[j − i]. Length 4: 2 + 2 → 5 + 5 = 10 beats a single 4 (9). Length 8: 2 + 6 → 5 + 17 = 22 beats an uncut rod (20). This is an unbounded knapsack, O(n²).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic