Data Structures & AlgorithmsVery hardCodeforces Div2 C/D · Amazon SDE OA
Items (weight, value) are (5,10), (4,7), (6,12), (3,4) and the knapsack capacity is 10. Each item may be taken at most once. Run the exact 0/1 knapsack DP and report the best value.
Items (weight, value) are (5,10), (4,7), (6,12), (3,4) and the knapsack capacity is 10. Each item may be taken at most once. Run the exact 0/1 knapsack DP and report the best value.
items=[(5,10),(4,7),(6,12),(3,4)]
W=10
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(dp[W])What is printed?- A. 19
- B. 17
- C. 20
- D. 22
Correct answer: A. 19
The exact 0/1 DP iterates capacities downward so each item is used once. Density greedy is not exact here, unbounded knapsack lets an item repeat (5+5 gives 20), and reading the capacity as 11 is an off-by-one slip.
More Coding Interview Problems questions
- Binary string s = "1101001110001011". Find the length of the longest contiguous substring that contains equally many 0s and 1s. python…
- Intervals (start, end) are compatible when one ends at or before the other starts. Run the earliest-finish greedy on the list below and…
- Coins of denominations 1, 3 and 4 are available with unlimited supply. For the amount 6, run the DP that finds the minimum number of coins…
- Array a = [1, 3, 2, 3, 1, 4, 5, 2]. Subsequences are chosen by index (positions may repeat values). Count the strictly increasing…
- Two strings are "intention" and "execution". Compute the minimum cost to turn the first into the second, where insertion and deletion cost…
- A staircase is climbed with steps of size 1, 3 or 4 (order of steps matters). How many distinct ordered sequences of steps reach exactly…