Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: A cable of length n is cut into pieces; prices[k − 1] is the price of a piece of length k. Maximise revenue (unbounded knapsack).

Problem: A cable of length n is cut into pieces; prices[k − 1] is the price of a piece of length k. Maximise revenue (unbounded knapsack).
def rod(prices, n):
    dp = [0] * (n + 1)
    for length in range(1, n + 1):
        dp[length] = max(prices[k - 1] + dp[length - k] for k in range(1, min(length, len(prices)) + 1))
    return dp[n]
print(rod([2, 6, 7, 10], 6), rod([3, 5, 8, 9], 4))
What is printed?
  1. A. 16 12
  2. B. 18 12
  3. C. 17 12
  4. D. 18 9

Correct answer: B. 18 12

dp[L] = best over the length k of the first piece. Prices per unit: 2, 3, 2.33, 2.5 for the first cable, so three 2-pieces give 6 + 6 + 6 = 18 (4 + 2 gives 16). Second: four 1-pieces give 12, beating the whole cable (9) and 3 + 1 (11). O(n · m).

More Coding Interview Problems questions

Exams that ask this topic