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. we have only one quantity of each item.
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 don’t pick it (0-1 property).

example:
n=3
w=4
val[n]={1 2 3}
weight[n]={4 5 1}

answer is 3

we will use dynamic programming to solove this question:
y is no of test cases

//c++ code 
#include <iostream>
using namespace std;


void knap(int n, int w, int val[],int weight[])
{
      int t[n+1][w+1];     
   
   
   //fill  0th rows and coloumns with zero.
   for(int i=0;i<=n;i++)      
      t[i][0]=0;
      
   for(int j=0;j<=w;j++)
      t[0][j]=0;
      
      
       for(int i=1;i<=n;i++)
       {
           for(int j=1;j<=w;j++)
           {
               if(j<weight[i])
               t[i][j]=t[i-1][j];
               else
               t[i][j]=max((val[i]+t[i-1][j-weight[i]]),t[i-1][j]);
           }
       }
     
      cout<<t[n][w]<<endl; //last element
    
}
int main() {int y; cin>>y;
while(y--)
{ int n; cin>>n;
   int w; cin>>w;
   int val[n];int weight[n];
   
   for(int i=1;i<=n;i++)
   cin>>val[i];
   
   for(int i=1;i<=n;i++)
   cin>>weight[i]; 
   
 knap(n,w,val,weight);
    
}
return 0;
}
darkmode