Complete the code to initialize the dp array with zeros for the knapsack capacity.
const dp = new Array(capacity + 1).fill([1]);
We fill the dp array with 0 because initially, the maximum value for any capacity is zero.
Complete the code to loop through all capacities from 1 to the given capacity.
for (let w = 1; w <= [1]; w++) {
We loop from 1 to capacity to fill dp for all sub-capacities.
Fix the error in the condition to check if the current item can fit in the knapsack.
if (weights[i] [1] w) {
The item weight must be less than or equal to the current capacity to fit.
Fill both blanks to update dp[w] with the maximum value including the current item.
dp[w] = Math.max(dp[w], dp[w - [1]] + [2]);
We subtract the item's weight from current capacity and add its value to dp.
Fill all three blanks to complete the unbounded knapsack function.
function unboundedKnapsack([1], [2], capacity) { const dp = new Array(capacity + 1).fill(0); for (let w = 1; w <= capacity; w++) { for (let i = 0; i < [3]; i++) { if (weights[i] <= w) { dp[w] = Math.max(dp[w], dp[w - weights[i]] + values[i]); } } } return dp[capacity]; }
The function takes weights and values arrays and capacity. The inner loop runs for all items using weights.length.
