-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGFG 0 - 1 Knapsack Problem
61 lines (53 loc) · 1.33 KB
/
GFG 0 - 1 Knapsack Problem
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
57
58
59
60
61
class Solution
{
public:
//Function to return max value that can be put in knapsack of capacity W.
int solve(int W, int wt[], int val[], int n,vector<vector<int>>&dp)
{
// Your code here
// base condition
if(n==0||W==0)
return 0;
if(dp[n][W]!=-1)
return dp[n][W];
if(wt[n-1]<=W)
{
return dp[n][W]= max(val[n-1]+solve(W-wt[n-1],wt,val,n-1,dp),solve(W,wt,val,n-1,dp));
}
else return dp[n][W]= solve (W,wt,val,n-1,dp);
}
int knapSack(int W, int wt[], int val[], int n)
{
// Your code here
// base condition
vector<vector<int>>dp(n+1,vector<int>(W+1,-1));
solve(W,wt,val,n,dp);
return dp[n][W];
}
};
//{ Driver Code Starts.
int main()
{
//taking total testcases
int t;
cin>>t;
while(t--)
{
//reading number of elements and weight
int n, w;
cin>>n>>w;
int val[n];
int wt[n];
//inserting the values
for(int i=0;i<n;i++)
cin>>val[i];
//inserting the weights
for(int i=0;i<n;i++)
cin>>wt[i];
Solution ob;
//calling method knapSack()
cout<<ob.knapSack(w, wt, val, n)<<endl;
}
return 0;
}
// } Driver Code Ends