Skip to content

Commit 165a375

Browse files
authored
Knapsack_Dynamic
Knapsack_DynamicProgramming in C++ done
1 parent 92529a5 commit 165a375

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#include<iostream>
2+
using namespace std;
3+
int main()
4+
{
5+
int P[]={0,1,2,5};
6+
int Wt[]={0,2,3,4};
7+
int m=5,n=3;
8+
int K[4][6];
9+
10+
for(int i=0;i<=n;i++)
11+
{
12+
for(int j=0;j<=m;j++)
13+
{
14+
if(i==0 || j==0)
15+
K[i][j]=0;
16+
else if(Wt[i]<=j)
17+
K[i][j]=max(K[i-1][j],K[i-1][j-Wt[i]]+P[i]);
18+
else
19+
K[i][j]=K[i-1][j];
20+
}
21+
}
22+
cout<<"Weight: ";
23+
for(int i=1;i<=n;i++)
24+
{
25+
cout<<Wt[i]<<" ";
26+
}
27+
cout<<"\nProfit: ";
28+
for(int i=1;i<=n;i++)
29+
{
30+
cout<<P[i]<<" ";
31+
}
32+
cout<<"\n\nMAX Profit: "<<K[n][m];
33+
return 0;
34+
}

0 commit comments

Comments
 (0)