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))- A. 9 [1, 2]
- B. 9 [0, 3]
- C. 8 [0, 3]
- 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).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- What is printed? (number of BSTs vs number of binary heaps on keys 1..4) python from math import comb from functools import lrucache…
- What is printed? (diameter of an unweighted tree with two BFS passes) python from collections import deque edges = [(1, 2), (1, 3), (2…
- What is printed? (articulation points by brute force removal) python edges = [(0, 1), (1, 2), (2, 0), (1, 3), (3, 4), (4, 5), (5, 3), (5…
- What is printed? (strongly connected components count, Kosaraju) python g = {0: [1], 1: [2], 2: [0, 3], 3: [4], 4: [5], 5: [3], 6: [5, 7]…
- What is printed? (greedy fractional knapsack) python items = [(10, 60), (20, 100), (30, 120)] # (weight, value) cap, total = 50, 0.0 for…
- What is printed? (minimum platforms / overlapping intervals with a heap) python import heapq iv = sorted([(1, 4), (2, 3), (3, 6), (5, 7)…