Finished
1{
12//
23// This is only a SKELETON file for the 'Knapsack' exercise. It's been provided as a
34// convenience to get you started writing code faster.
89 * @param {{weight: number, value: number}[]} items
910 * @returns {number}
1011 */
11export const knapsack = (maximumWeight, items) => {
12 throw new Error('Remove this line and implement the function');
12const knapsack = (maximumWeight, items) => {
13 // Edge Case: Empty items list
14 if (!items || items.length === 0) {
15 return 0;
16 }
17
18 // Edge Case: Knapsack capacity of zero or negative
19 if (maximumWeight <= 0) {
20 return 0;
21 }
22
23 const n = items.length;
24 // Create a 2D array for dynamic programming
25 // dp[i][w] represents the maximum value with first i items and weight limit w
26 const dp = Array(n + 1)
27 .fill(0)
28 .map(() => Array(maximumWeight + 1).fill(0));
29
30 // Fill the dp table
31 for (let i = 1; i <= n; i++) {
32 const currentItem = items[i - 1];
33
34 // Edge Case: Item with weight exceeding capacity
35 if (currentItem.weight > maximumWeight) {
36 dp[i] = [...dp[i - 1]];
37 continue;
38 }
39
40 for (let w = 0; w <= maximumWeight; w++) {
41 // Don't take the item
42 dp[i][w] = dp[i - 1][w];
43
44 // Take the item if it fits
45 if (currentItem.weight <= w) {
46 const valueWithItem = dp[i - 1][w - currentItem.weight] + currentItem.value;
47 dp[i][w] = Math.max(dp[i][w], valueWithItem);
48 }
49 }
50 }
51
52 return dp[n][maximumWeight];
1353};
54
55// Handled Edge Cases: empty items list, knapsack capacity of zero, items with weight exceeding capacity
56
57module.exports = { knapsack };
58}
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.