Skip to content

Commit

Permalink
0-1 kanpsack problem
Browse files Browse the repository at this point in the history
  • Loading branch information
NasreenParween committed Jul 15, 2022
1 parent 4aa483a commit c0c94a5
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions DAA_01_Knapsack1_problem.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#include<iostream>
using namespace std;
int max(int a,int b)
{
return (a>b)?a:b;
}
int knapsack(int w,int val[],int wt[],int n)
{
if(n==0 || w==0)
{
return 0;
}
if(wt[n-1]>w)
{
return knapsack(w,val,wt,n-1);
}
else
{
return max(val[n-1]+knapsack(w-wt[n-1],val,wt,n-1),knapsack(w,val,wt,n-1));
}
}
int main()
{
int val[20],wt[20];
int w,n;
cout<<"Enter array size of value and weight: ";
cin>>n;
cout<<"\nEnter elements of value array: ";
for(int i=0;i<n;i++)
{
cin>>val[i];
}
cout<<"\nEnter elements of weight array: ";
for(int i=0;i<n;i++)
{
cin>>wt[i];
}
cout<<"\nEnter knapsack capacity: ";
cin>>w;
cout<<"\nElements of value array are: \n";
for(int i=0;i<n;i++)
{
cout<<"val["<<i<<"]= "<<val[i]<<"\n";
}
cout<<"\nElements of weight array are: \n";
for(int i=0;i<n;i++)
{
cout<<"wt["<<i<<"]= "<<wt[i]<<"\n";
}
cout<<"\nMaximum total value in knapsack: ";
cout<<knapsack(w,val,wt,n);
}

0 comments on commit c0c94a5

Please sign in to comment.