Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Cut a rod of length 7 into integer pieces to maximise total price, where price[i] is the price of a piece of length i + 1 (unbounded knapsack).

Problem: Cut a rod of length 7 into integer pieces to maximise total price, where price[i] is the price of a piece of length i + 1 (unbounded knapsack).
def rod(price, n):
    dp = [0] * (n + 1)
    for L in range(1, n + 1):
        dp[L] = max(price[i] + dp[L - i - 1] for i in range(L))
    return dp[n]
print(rod([2, 5, 7, 8, 10, 13, 15], 7))
What is printed?
  1. A. 17
  2. B. 15
  3. C. 32
  4. D. 14

Correct answer: A. 17

Length 2 has the best price per unit (2.5): 2 + 2 + 2 + 1 gives 5 + 5 + 5 + 2 = 17, and 2 + 2 + 3 also gives 17. Selling the rod whole (or allowing each length only once, 0/1 knapsack) gives 15, cutting it into seven unit pieces gives 14, and the index slip dp[L − i] instead of dp[L − i − 1] inflates the result to 32.

More Coding Interview Problems questions

Exams that ask this topic