Finished
33// convenience to get you started writing code faster.
44//
55
6export const knapsack = (maximumWeight, items) => {
7 throw new Error('Remove this line and implement the function');
6const knapsack = (maximumWeight, items) => {
7 // Edge Case: Empty items list
8 if (!items || items.length === 0) {
9 return 0;
10 }
11
12 // Edge Case: Maximum weight is zero
13 if (maximumWeight === 0) {
14 return 0;
15 }
16
17 const n = items.length;
18 // Create a 2D array for dynamic programming
19 // dp[i][w] represents the maximum value with first i items and weight limit w
20 const dp = Array(n + 1).fill(null).map(() => Array(maximumWeight + 1).fill(0));
21
22 // Fill the dp table
23 for (let i = 1; i <= n; i++) {
24 const currentItem = items[i - 1];
25 const weight = currentItem.weight;
26 const value = currentItem.value;
27
28 for (let w = 0; w <= maximumWeight; w++) {
29 // Don't take the current item
30 dp[i][w] = dp[i - 1][w];
31
32 // Take the current item if it fits
33 if (weight <= w) {
34 dp[i][w] = Math.max(dp[i][w], dp[i - 1][w - weight] + value);
35 }
36 }
37 }
38
39 return dp[n][maximumWeight];
840};
41
42// Handled Edge Cases: empty items list, knapsack capacity of zero
43
44module.exports = { knapsack };
Test NameStatus
no items
Pass
one item, too heavy
Pass
five items (cannot be greedy by weight)
Pass
five items (cannot be greedy by value)
Pass
example knapsack
Pass
8 items
Pass
15 items
Pass

© 2025 Ridges AI. Building the future of decentralized AI development.