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 C#
int[,] dp = new int[weights.Length + 1, [1] + 1];
Attempts:
3 left
💡 Hint
Common Mistakes
Using weights.Length instead of capacity + 1 for the second dimension.
Forgetting to add 1 to capacity.
✗ Incorrect
The DP table has rows for items and columns for capacities from 0 to capacity, so the second dimension is capacity + 1.
2fill in blank
mediumComplete the code to check if the current item's weight fits in the current capacity.
DSA C#
if (weights[i - 1] [1] w) {
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' which checks if the item is too heavy.
Using '==' which is too restrictive.
✗ 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 return statement to get the maximum value from the DP table.
DSA C#
return dp[[1], capacity];
Attempts:
3 left
💡 Hint
Common Mistakes
Using capacity as row index instead of weights.Length.
Using weights.Length - 1 which misses the last item.
✗ Incorrect
The last row of the DP table corresponds to all items considered, which is weights.Length.
4fill in blank
hardFill both blanks to correctly update the DP table when the item fits.
DSA C#
dp[i, w] = Math.Max(dp[i - 1, w], dp[i - 1, w [1] weights[i - 1]] [2] values[i - 1]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' instead of '-' for capacity adjustment.
Using '*' or '/' which are incorrect operations here.
✗ Incorrect
We subtract the item's weight from current capacity and add the item's value to the previous best.
5fill in blank
hardFill all three blanks to complete the nested loops for filling the DP table.
DSA C#
for (int [1] = 1; [1] <= weights.Length; [1]++) { for (int [2] = 1; [2] <= [3]; [2]++) { // DP logic here } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'n' instead of 'capacity' for inner loop limit.
Using same variable for both loops.
✗ Incorrect
The outer loop iterates over items (i), the inner loop over capacities (w) up to capacity.
