[Geeks for Geeks] 0 - 1 Knapsack Problem

0 - 1 Knapsack Problem

You are given weights and values of N items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Note that we have only one quantity of each item.
In other words, given two integer arrays val[0..N-1] and wt[0..N-1] which represent values and weights associated with N items respectively. Also given an integer W which represents knapsack capacity, find out the maximum value subset of val[] such that sum of the weights of this subset is smaller than or equal to W. You cannot break an item, either pick the complete item or dont pick it (0-1 property).

  • Time : O(n * w)
  • Space : O(w)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
//Function to return max value that can be put in knapsack of capacity W.
int knapSack(int W, int wt[], int val[], int n) {
int res = 0;
vector<int> dp(W + 1, INT_MIN);
dp[0] = 0;

for(int i = 0; i < n; i++) {
int w = wt[i], v = val[i];
for(int i = W; i >= w; i--) {
dp[i] = max(dp[i], dp[i-w] + v);
res = max(res, dp[i]);
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/20/PS/GeeksforGeeks/0-1-knapsack-problem/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.