Knapsack 01 Dynamic Programming Typed

Solve the 0-1 knapsack problem using typed dynamic programming with a rolling array for space optimization.

TypescriptData Integrity

Code

typescriptsnippet
13 lines
function knapsack01(weights: number[], values: number[], capacity: number): number {
  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];
}

What the code does

Count the function knapsack01 as the entire surface area of Knapsack 01 Dynamic Programming Typed.

Two loops stack here: for (let i = 0; i < n; i++) selects, for (let w = 0; w <= capacity; w++) processes.

Applying it

The main signature reads function knapsack01(weights: number[], values: number[], capacity: number)

Statements that matter

return dp[capacity];

Interactive Tools for This Topic

FAQ

Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. The file defines `knapsack01` at load time.