forked from codemistic/Data-Structures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0-1_Knapsack.cpp
56 lines (35 loc) · 1.08 KB
/
0-1_Knapsack.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <bits/stdc++.h>
using namespace std;
int knapsack(vector<int>& wt, vector<int>& val, int n, int W){
vector<int> prev(W+1,0);
//Base Condition
for(int i=wt[0]; i<=W; i++){
prev[i] = val[0];
}
for(int ind =1; ind<n; ind++){
for(int cap=W; cap>=0; cap--){
int notTaken = 0 + prev[cap];
int taken = INT_MIN;
if(wt[ind] <= cap)
taken = val[ind] + prev[cap - wt[ind]];
prev[cap] = max(notTaken, taken);
}
}
return prev[W];
}
int main() {
vector<int> wt = {1,2,4,5};
vector<int> val = {5,4,8,6};
int W=5;
int n = wt.size();
cout<<"The Maximum value of items, thief can steal is " <<knapsack(wt,val,n,W);
}
/*
Output:
The Maximum value of items, thief can steal is 13
Time Complexity: O(N*W)
Reason: There are two nested loops.
Space Complexity: O(W)
Reason: We are using an external array of size ‘W+1’ to store only one row
*/
// contributed by Sourav Naskar