Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the DP array with zeros.
DSA C++
int dp[n+1] = {0}; for (int i = 0; i <= n; i++) { dp[i] = [1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing dp[i] with 1 or -1 instead of 0.
Using the loop variable i as the value.
✗ Incorrect
The DP array should be initialized with 0 because initially, the maximum value for any capacity is zero.
2fill in blank
mediumComplete the code to iterate over all capacities from 1 to n.
DSA C++
for (int w = 1; w <= [1]; w++) { // logic here }
Attempts:
3 left
💡 Hint
Common Mistakes
Using an undefined variable like capacity or weight.
Looping beyond the capacity n.
✗ Incorrect
The loop should run from 1 to n, where n is the total capacity of the knapsack.
3fill in blank
hardFix the error in the condition to check if the current item's weight fits in the current capacity.
DSA C++
if (wt[i] [1] w) { dp[w] = max(dp[w], dp[w - wt[i]] + val[i]); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using > or == instead of <=.
Using < which excludes equal weight cases.
✗ Incorrect
We check if the item's weight is less than or equal to the current capacity to decide if it can be included.
4fill in blank
hardFill both blanks to update the dp array correctly inside the nested loops.
DSA C++
dp[w] = max(dp[w], dp[w [1] wt[i]] [2] val[i]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using + instead of - for the index calculation.
Using * or / instead of + for adding the item's value.
✗ Incorrect
We subtract the item's weight from w to find the remaining capacity and add the item's value to the dp value of that remaining capacity.
5fill in blank
hardFill all three blanks to complete the nested loops for the unbounded knapsack solution.
DSA C++
for (int i = 0; i [1] n; i++) { for (int w = 1; w [2] capacity; w++) { if (wt[i] [3] w) { dp[w] = max(dp[w], dp[w - wt[i]] + val[i]); } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using <= in the outer loop causing out of bounds.
Using < in the inner loop missing the last capacity.
Using > or >= incorrectly in the condition.
✗ Incorrect
The outer loop runs from 0 to n-1 (i < n). The inner loop runs from 1 to capacity (w <= capacity). The condition checks if the item's weight is less than or equal to w.
