Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the DP table for the 0 1 Knapsack problem.
DSA Java
int[][] dp = new int[[1] + 1][W + 1];
Attempts:
3 left
💡 Hint
Common Mistakes
Using W (capacity) as the number of rows instead of n (items).
Using weight or value arrays as dimensions.
✗ Incorrect
The DP table has rows equal to the number of items (n) plus one for the base case.
2fill in blank
mediumComplete the code to check if the current item's weight fits in the knapsack capacity.
DSA Java
if (weight[i - 1] [1] w) {
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' which checks if item weight is greater than capacity.
Using '==' which is too strict.
✗ Incorrect
We check if the item's weight is less than or equal to the current capacity to decide if we can include it.
3fill in blank
hardFix the error in the code to correctly update the DP table when including the current item.
DSA Java
dp[i][w] = Math.max(dp[i - 1][w], dp[i - 1][w - [1]] + value[i - 1]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using weight[i] causes index out of bounds.
Using value instead of weight for capacity subtraction.
✗ Incorrect
We subtract the weight of the current item (weight[i - 1]) from capacity w to find the remaining capacity.
4fill in blank
hardFill both blanks to complete the loop headers for filling the DP table.
DSA Java
for (int i = 1; i [1] n + 1; i++) { for (int w = 0; w [2] W + 1; w++) {
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' causes index out of bounds.
Using '>' or '>=' reverses loop direction.
✗ Incorrect
Loops run from 1 to n and 0 to W using '<' to avoid going out of bounds.
5fill in blank
hardFill both blanks to complete the return statement that outputs the maximum value achievable.
DSA Java
return dp[[1]][[2]];
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 or weight.length instead of n for rows.
Using 0 instead of W for capacity.
✗ Incorrect
The answer is at dp[n][W], representing all items and full capacity.
