Skip to content

Commit caf6f04

Browse files
🐛 fix(integerKnapsack): First draft.
1 parent e068668 commit caf6f04

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

src/integerKnapsack.js

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,18 @@
11
import assert from 'assert';
22

3-
const integerKnapsack = (v, w, n, W) => {
3+
const integerKnapsack = (v, w, n, W, m = new w.constructor(W + 1).fill(0)) => {
44
assert(v.length === n);
55
assert(w.length === n);
66
assert(Number.isInteger(W) && W >= 0);
7-
return 0;
7+
assert(m.length >= W + 1);
8+
for (let i = 0; i < n; ++i) {
9+
const x = w[i];
10+
for (let j = W; j >= x; --j) {
11+
m[j] = Math.max(m[j], m[j - x] + v[i]);
12+
}
13+
}
14+
15+
return m[W];
816
};
917

1018
export default integerKnapsack;

0 commit comments

Comments
 (0)