| 3 | 3 | // convenience to get you started writing code faster. |
| 4 | 4 | // |
| 5 | 5 | |
| 6 | | export const knapsack = (maximumWeight, items) => { |
| 7 | | throw new Error('Remove this line and implement the function'); |
| 6 | const 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]; |
| 8 | 40 | }; |
| 41 | |
| 42 | // Handled Edge Cases: empty items list, knapsack capacity of zero |
| 43 | |
| 44 | module.exports = { knapsack }; |