8000 Merge pull request #1174 from Aayushdh99/patch-10 · glitches-coder/Algorithms@a4c3c78 · GitHub
[go: up one dir, main page]

Skip to content

Commit a4c3c78

Browse files
Merge pull request VAR-solutions#1174 from Aayushdh99/patch-10
Create Extended Knapsack Problem.cpp
2 parents 5a07a6e + 8e764c2 commit a4c3c78

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// C++ code for the extended
2+
// Knapsack Approach
3+
4+
#include <bits/stdc++.h>
5+
using namespace std;
6+
#define N 100
7+
#define W 100
8+
#define K 100
9+
10+
int dp[N][W][K];
11+
int solve(int profit[],
12+
int weight[],
13+
int n, int max_W,
14+
int max_E)
15+
{
16+
17+
// for each element given
18+
for (int i = 1; i <= n; i++) {
19+
20+
// For each possible
21+
// weight value
22+
for (int j = 1; j <= max_W; j++) {
23+
24+
// For each case where
25+
// the total elements are
26+
// less than the constraint
27+
for (int k = 1; k <= max_E; k++) {
28+
29+
// To ensure that we dont
30+
// go out of the array
31+
if (j >= weight[i]) {
32+
33+
dp[i][j][k]
34+
= max(
35+
dp[i - 1][j][k],
36+
dp[i - 1]
37+
[j - weight[i]]
38+
[k - 1]
39+
+ profit[i]);
40+
}
41+
else {
42+
dp[i][j][k]
43+
= dp[i - 1][j][k];
44+
}
45+
}
46+
}
47+
}
48+
49+
return dp[n][max_W][max_E];
50+
}
51+
52+
// Driver Code
53+
int main()
54+
{
55+
56+
memset(dp, 0, sizeof(dp));
57+
58+
int n = 5;
59+
int profit[] = { 2, 7, 1, 5, 3 };
60+
int weight[] = { 2, 5, 2, 3, 4 };
61+
int max_weight = 8;
62+
int max_element = 2;
63+
cout << solve(profit,
64+
weight, n,
65+
max_weight,
66+
max_element)
67+
<< "\n";
68+
69+
return 0;
70+
}

0 commit comments

Comments
 (0)
0