Data Structures & AlgorithmsVery hardCodeforces Div2 D · knapsack
Problem: Items (weight, value) are (2,3), (3,4), (4,5), and each may be used at most once. Capacity W = 7. Run the code below to find the maximum value.
Problem: Items (weight, value) are (2,3), (3,4), (4,5), and each may be used at most once. Capacity W = 7. Run the code below to find the maximum value.
items = [(2, 3), (3, 4), (4, 5)]
W = 7
best = [0] * (W + 1)
for w, v in items:
for c in range(W, w - 1, -1):
best[c] = max(best[c], best[c - w] + v)
print(best[W])What is printed?- A. 10
- B. 12
- C. 8
- D. 9
Correct answer: D. 9
Each item is used at most once, so the best set at capacity 7 is {3, 4} with value 4 + 5 = 9 (the pair {2, 4} gives 8 and {2, 3} gives 7). Letting items repeat would give 10 via 2 + 2 + 3, which is the trap for unbounded knapsack.
More Coding Interview Problems questions
- Problem: How many ways can a staircase of 8 steps be climbed if each move climbs 1, 3 or 4 steps? Run the DP below. python ways = [0] 9…
- Problem: Jobs are given as (deadline, profit): (2,100), (1,19), (2,27), (1,25), (3,15). Each job takes one unit slot and must finish by…
- Problem: Compute C(10, 3) mod 7 using Lucas' theorem, where 7 is prime. What is the result?
- Problem: What is 3^100 mod 10?
- Problem: How many positive divisors does 2^4 3^2 5 7 have?
- Problem: Minimum insertions of brackets to make the string '(()))(' valid, found by this greedy scan? python s = '(()))(' bal = 0 ins = 0…