Skip to content

Commit cc88cbc

Browse files
Merge pull request #1 from alhussain-shaikh/alhussain-shaikh-patch-1
Create Knapsack.js
2 parents 0315c8a + 3dce58e commit cc88cbc

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

Dynamic-Programming/Knapsack.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
2+
function knapSack(capacity, weights, values, n) {
3+
let i, w;
4+
let K = Array(n+1).fill().map(() => Array(capacity+1).fill(0));
5+
6+
// Build table K[][] in bottom up manner
7+
for (i = 0; i <= n; i++) {
8+
for (w = 0; w <= capacity; w++) {
9+
if (i==0 || w==0)
10+
K[i][w] = 0;
11+
else if (weights[i-1] <= w)
12+
K[i][w] = Math.max(values[i-1] + K[i-1][w-weights[i-1]], K[i-1][w]);
13+
else
14+
K[i][w] = K[i-1][w];
15+
}
16+
}
17+
return K[n][capacity];
18+
}

0 commit comments

Comments
 (0)