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?
  1. A. 8
  2. B. 11
  3. C. 12
  4. 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

Exams that ask this topic