Skip to content

Commit bf34027

Browse files
🚀 perf(integerKnapsack): Scan memory from left to right.
1 parent a6b4777 commit bf34027

File tree

1 file changed

+4
-3
lines changed

1 file changed

+4
-3
lines changed

src/integerKnapsack.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,13 @@ const integerKnapsack = (v, w, n, W, m = new w.constructor(W + 1).fill(0)) => {
77
assert(m.length >= W + 1);
88
for (let i = 0; i < n; ++i) {
99
const x = w[i];
10-
for (let j = W; j >= x; --j) {
11-
m[j] = Math.max(m[j], m[j - x] + v[i]);
10+
const s = W - x;
11+
for (let j = 0; j <= s; ++j) {
12+
m[j] = Math.max(m[j], m[j + x] + v[i]);
1213
}
1314
}
1415

15-
return m[W];
16+
return m[0];
1617
};
1718

1819
export default integerKnapsack;

0 commit comments

Comments
 (0)