Knapsack 01 Dynamic Programming (JavaScript)

Solve the 0-1 knapsack problem using dynamic programming with a one dimensional rolling array to reduce space complexity.

JavascriptData Integrity

Code

javascriptsnippet
15 lines
function knapsack01(weights, values, capacity) {
  const n = weights.length;
  let dp = new Array(capacity + 1).fill(0);
  for (let i = 0; i < n; i++) {
    const next = new Array(capacity + 1).fill(0);
    for (let w = 0; w <= capacity; w++) {
      next[w] = dp[w];
      if (w >= weights[i] && dp[w - weights[i]] + values[i] > next[w]) {
        next[w] = dp[w - weights[i]] + values[i];
      }
    }
    dp = next;
  }
  return dp[capacity];
}

How it works

Count the function knapsack01 as the entire surface area of Knapsack 01 Dynamic Programming (JavaScript).

Iteration is nested: for (let i = 0; i < n; i++) frames the pass, for (let w = 0; w <= capacity; w++) does the per-item step.

Using it

The primary signature is function knapsack01(weights, values, capacity)

Key statements

return dp[capacity];

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. The file defines `knapsack01` at load time.