Skip to content

Commit aee0135

Browse files
authored
Merge pull request #34 from shubhammarathe15/patch-1
Create 0-1_Knapsack.cpp
2 parents a378856 + 14dfdae commit aee0135

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

0-1_Knapsack.cpp

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
int knapSack(int W, int wt[], int val[], int n)
4+
{
5+
// making and initializing dp array
6+
int dp[W + 1];
7+
memset(dp, 0, sizeof(dp));
8+
9+
for (int i = 1; i < n + 1; i++) {
10+
for (int w = W; w >= 0; w--) {
11+
12+
if (wt[i - 1] <= w)
13+
// finding the maximum value
14+
dp[w] = max(dp[w],
15+
dp[w - wt[i - 1]] + val[i - 1]);
16+
}
17+
}
18+
return dp[W]; // returning the maximum value of knapsack
19+
}
20+
int main()
21+
{
22+
int val[] = { 60, 100, 120 };
23+
int wt[] = { 10, 20, 30 };
24+
int W = 50;
25+
int n = sizeof(val) / sizeof(val[0]);
26+
cout << knapSack(W, wt, val, n);
27+
return 0;
28+
}

0 commit comments

Comments
 (0)