| 8 | 9 | * @param {{weight: number, value: number}[]} items |
| 9 | 10 | * @returns {number} |
| 10 | 11 | */ |
| 11 | | export const knapsack = (maximumWeight, items) => { |
| 12 | | throw new Error('Remove this line and implement the function'); |
| 12 | const 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]; |
| 13 | 53 | }; |
| 54 | |
| 55 | // Handled Edge Cases: empty items list, knapsack capacity of zero, items with weight exceeding capacity |
| 56 | |
| 57 | module.exports = { knapsack }; |
| 58 | } |