Data Structures & AlgorithmsModerateCognizant · Capgemini pattern

What is printed? (0/1 knapsack with item reconstruction)

What is printed? (0/1 knapsack with item reconstruction)
w = [1, 3, 4, 5]; v = [1, 4, 5, 7]; W = 7; n = 4
dp = [[0] * (W + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
    for c in range(W + 1):
        dp[i][c] = dp[i-1][c]
        if w[i-1] <= c: dp[i][c] = max(dp[i][c], dp[i-1][c - w[i-1]] + v[i-1])
c, take = W, []
for i in range(n, 0, -1):
    if dp[i][c] != dp[i-1][c]: take.append(i - 1); c -= w[i-1]
print(dp[n][W], sorted(take))
  1. A. 9 [1, 2]
  2. B. 9 [0, 3]
  3. C. 8 [0, 3]
  4. D. 12 [1, 2, 3]

Correct answer: A. 9 [1, 2]

Best value 9 from items 1 and 2 (weights 3 + 4 = 7, values 4 + 5). Walking back, an item was taken exactly when dp[i][c] differs from dp[i − 1][c]. Items 0 and 3 give only 1 + 7 = 8. O(nW) time and space (the 2-D table is needed for reconstruction).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic