Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE
Problem: 0/1 knapsack – maximise value within capacity W.
Problem: 0/1 knapsack – maximise value within capacity W.
int knap(vector<int> w, vector<int> v, int W) {
vector<int> dp(W + 1, 0);
for (int i = 0; i < w.size(); i++)
for (int c = W; c >= w[i]; c--)
dp[c] = max(dp[c], dp[c - w[i]] + v[i]);
return dp[W];
}
// knap({1, 3, 4, 5}, {1, 4, 5, 7}, 7)What does the call return?- A. 8
- B. 11
- C. 12
- D. 9
Correct answer: D. 9
Best subset within weight 7: weights 3 + 4 → values 4 + 5 = 9; weights 5 + 1 give only 8. Taking the item with the best value/weight ratio first is the greedy trap for 0/1 items. O(n·W) time, O(W) space.
More Coding Interview Problems questions
- Problem: Find the length of the longest strictly increasing subsequence of daily sales. python from bisect import bisectleft def lis(a)…
- Problem: Find the length of the longest common subsequence of two version strings. python def lcs(a, b): dp = [[0] (len(b) + 1) for in…
- Problem: Find the minimum number of insert, delete or replace operations to convert one word to another (edit distance). python def…
- Problem: Count paths from the top-left to the bottom-right of a grid moving only right or down, where 1 marks a blocked cell. python def…
- Problem: Find the minimum path sum from the top-left to the bottom-right of a cost grid (moves: right or down). python def minpath(g): R…
- Problem: Count the ways to decode a digit string where 'A' = 1 … 'Z' = 26. python def decode(s): prev2, prev1 = 1, (1 if s[0] != '0' else…