Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the DP array for the knapsack problem.
DSA Javascript
const dp = new Array(n + 1).fill().map(() => new Array([1] + 1).fill(0));
Attempts:
3 left
💡 Hint
Common Mistakes
Using the number of items 'n' instead of the capacity 'W' for the second dimension.
Initializing with zeros incorrectly.
✗ Incorrect
We create a 2D array dp with dimensions (n+1) x (W+1), where W is the knapsack capacity.
2fill in blank
mediumComplete the code to check if the current item's weight fits in the knapsack capacity.
DSA Javascript
if (weights[i - 1] [1] w) {
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' which means the item is heavier than capacity.
Using '==' which is too strict.
✗ Incorrect
We check if the weight of the current item is less than or equal to the current capacity to decide if we can include it.
3fill in blank
hardFix the error in updating the dp table when including the current item.
DSA Javascript
dp[i][w] = Math.max(dp[i - 1][w], dp[i - 1][w - [1]] + values[i - 1]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using weights[i] which is out of bounds.
Using values instead of weights.
✗ Incorrect
We subtract the weight of the current item (weights[i - 1]) from the capacity to find the remaining capacity.
4fill in blank
hardFill both blanks to complete the nested loops iterating over items and capacities.
DSA Javascript
for (let i = 1; i [1] n + 1; i++) { for (let w = 1; w [2] W + 1; w++) {
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' which causes index out of range.
Using '>' or '>=' which causes no iterations.
✗ Incorrect
We loop from 1 up to but not including n+1 and W+1, so we use '<' for both loops.
5fill in blank
hardFill both blanks to return the final maximum value after filling the dp table.
DSA Javascript
return dp[[1]][[2]];
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 which is the base case, not the answer.
Using weights.length instead of n.
✗ Incorrect
The answer is at dp[n][W], representing max value with all items and full capacity.
