Knapsack 01 Dynamic Programming (JavaScript)
Solve the 0-1 knapsack problem using dynamic programming with a one dimensional rolling array to reduce space complexity.
Code
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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.