-
Notifications
You must be signed in to change notification settings - Fork 131
Expand file tree
/
Copy pathknapsack.cpp
More file actions
79 lines (40 loc) · 1.07 KB
/
knapsack.cpp
File metadata and controls
79 lines (40 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include<iostream>
using namespace std;
int knapsack(int * weights, int * profits, int n, int maxWeight) {
int ** dp = new int * [n + 1];
for (int i = 0; i < n + 1; i++) {
dp[i] = new int[maxWeight + 1];
}
for (int i = 0; i < n + 1; i++) {
for (int j = 0; j < maxWeight + 1; j++) {
if (i == 0 || j == 0)
dp[i][j] = 0;
else if (weights[i - 1] > j) {
dp[i][j] = dp[i - 1][j];
}
else {
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weights[i - 1]] + profits[i - 1]);
}
}
}
return dp[n][maxWeight];
}
int main() {
int n;
cout<<"enter number ";
cin >> n;
int * weights = new int[n];
int * profits = new int[n];
cout<<"enter weights: ";
for (int i = 0; i < n; i++) {
cin >> weights[i];
}
cout<<"enter profit: ";
for (int i = 0; i < n; i++) {
cin >> profits[i];
}
int maxWeight;
cout<<"enter maximum weight : ";
cin >> maxWeight;
cout << knapsack(weights, profits, n, maxWeight);
}