Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern
0/1 knapsack, capacity 50: items (weight, value) = (10, 60), (20, 100), (30, 120). What do greedy-by-ratio and DP give?
0/1 knapsack, capacity 50: items (weight, value) = (10, 60), (20, 100), (30, 120). What do greedy-by-ratio and DP give?
items = [(10, 60), (20, 100), (30, 120)]
W = 50
cap, g = W, 0
for w, v in sorted(items, key=lambda x: -x[1] / x[0]):
if w <= cap: cap -= w; g += v
dp = [0] * (W + 1)
for w, v in items:
for c in range(W, w - 1, -1): dp[c] = max(dp[c], dp[c - w] + v)
print(g, dp[W])- A. 220 220
- B. 160 240
- C. 160 220
- D. 180 220
Correct answer: C. 160 220
Greedy by value/weight takes 10 (6/unit) and 20 (5/unit) for 160 and cannot fit 30. The DP finds 20 + 30 = 220. Greedy is optimal only for the fractional knapsack, where it would take 2/3 of the 30-kg item for 240.
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
- Activity selection: activities (start, finish). How many can one person attend, and which? python acts = [(1, 4), (3, 5), (0, 6), (5, 7)…
- Huffman coding: frequencies a:5, b:9, c:12, d:13, e:16, f:45. What is the total number of bits to encode the text? python import heapq f =…
- Longest common subsequence: what is the length and one LCS read back from the table (preferring the upper cell on ties)? python a, b =…
- Edit distance between "kitten" and "sitting", and between "intention" and "execution". What is printed? python def ed(a, b): prev =…
- Matrix chain order for dimensions 5 × 10, 10 × 3, 3 × 12, 12 × 5, 5 × 50, 50 × 6. What is the minimum number of scalar multiplications?…
- What is printed? (level-order traversal of the BST built from these keys) python def insert(t, k): if t is None: return [k, None, None] i…