Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare the DP table for the 0 1 Knapsack problem.
DSA C++
int dp[[1] + 1][W + 1];
Attempts:
3 left
💡 Hint
Common Mistakes
Using W (capacity) as the first dimension instead of n (items).
Forgetting to add 1 to n for zero items case.
✗ Incorrect
The DP table rows represent the number of items (n), so we declare dp with size n+1.
2fill in blank
mediumComplete the code to initialize the base case of the DP table.
DSA C++
for (int w = 0; w <= W; w++) dp[0][w] = [1];
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing dp[0][w] with w or W instead of 0.
Not initializing the base case at all.
✗ Incorrect
When zero items are considered, the maximum value is 0 for any capacity.
3fill in blank
hardFix the error in the condition to check if the current item's weight fits in the knapsack.
DSA C++
if (weight[i - 1] [1] w) {
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' which means the item is too heavy to include.
Using '==' which is too restrictive.
✗ Incorrect
We check if the item's weight is less than or equal to the current capacity w to decide if we can include it.
4fill in blank
hardFill both blanks to correctly update the DP table when including or excluding the current item.
DSA C++
dp[i][w] = std::max(dp[i - 1][w], dp[i - 1][w [1] weight[i - 1]] + [2][i - 1]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' instead of '-' for capacity calculation.
Using '*' or '/' which are incorrect operations here.
✗ Incorrect
We subtract the item's weight from w to find the remaining capacity and add the item's value when including it.
5fill in blank
hardFill all three blanks to complete the loop that builds the DP table for the 0 1 Knapsack problem.
DSA C++
for (int i = 1; i <= [1]; i++) { for (int w = 0; w <= [2]; w++) { if (weight[i - 1] <= w) { dp[i][w] = std::max(dp[i - 1][w], dp[i - 1][w - weight[i - 1]] + [3][i - 1]); } else { dp[i][w] = dp[i - 1][w]; } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping n and W in loops.
Using weight instead of value when adding item benefit.
✗ Incorrect
The outer loop runs over items (n), inner loop over capacities (W), and we add the item's value when including it.
