[Geeks for Geeks] Knapsack with Duplicate Items

Knapsack with Duplicate Items

Given a set of N items, each with a weight and a value, represented by the array w[] and val[] respectively. Also, a knapsack with weight limit W.
The task is to fill the knapsack in such a way that we can get the maximum profit. Return the maximum profit.

Note: Each item can be taken any number of times.

  • Time : O(nw)
  • Space : O(w)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int knapSack(int N, int W, int val[], int wt[]) {
vector<int> dp(W + 1, - 1);
int res = 0;
dp[0] = 0;
for(int i = 0; i < N; i++) {
for(int j = wt[i]; j <= W; j++) {
if(dp[j-wt[i]] == -1) continue;
dp[j] = max(dp[j], dp[j-wt[i]] + val[i]);
res = max(res, dp[j]);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/17/PS/GeeksforGeeks/knapsack-with-duplicate-items/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.