Knapsack 01 Dynamic Programming Typed
Solve the 0-1 knapsack problem using typed dynamic programming with a rolling array for space optimization.
Code
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
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
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free. The file defines `knapsack01` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.