-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathknapsack_top_down_dp.cpp
More file actions
35 lines (30 loc) · 855 Bytes
/
knapsack_top_down_dp.cpp
File metadata and controls
35 lines (30 loc) · 855 Bytes
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
#include <bits/stdc++.h>
using namespace std;
int Knapsack(int wt[], int val[], int W, int n) {
int t[n + 1][W + 1]; // DP matrix
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= W; j++) {
if (i == 0 || j == 0) // base case
t[i][j] = 0;
else if (wt[i - 1] <= j) { // current wt can fit in bag
int val1 = val[i - 1] + t[i - 1][j - wt[i - 1]]; // take current wt
int val2 = t[i - 1][j]; // skip current wt
t[i][j] = max(val1, val2);
}
else if (wt[i - 1] > j) // current wt doesn't fit in bag
t[i][j] = t[i - 1][j];
}
}
return t[n][W];
}
signed main() {
int n; cin >> n; // number of items
int val[n], wt[n]; // values and wts array
for (int i = 0; i < n; i++)
cin >> wt[i];
for (int i = 0; i < n; i++)
cin >> val[i];
int W; cin >> W; // capacity
cout << Knapsack(wt, val, W, n) << endl;
return 0;
}