Complete the code to declare the knapsack capacity variable.
int [1] = 50; // Maximum weight capacity of the knapsack
The variable capacity is commonly used to represent the maximum weight the knapsack can hold.
Complete the code to initialize the DP table with zeros.
for (int i = 0; i <= n; i++) { for (int w = 0; w <= [1]; w++) { dp[i][w] = 0; } }
The inner loop runs up to the knapsack capacity, so we use capacity here.
Fix the error in the condition to check if the current item's weight fits in the knapsack.
if (wt[i - 1] [1] w) { dp[i][w] = max(val[i - 1] + dp[i - 1][w - wt[i - 1]], dp[i - 1][w]); } else { dp[i][w] = dp[i - 1][w]; }
The item can be included only if its weight is less than or equal to the current capacity w.
Fill both blanks to complete the max function and the loop variable.
int max(int a, int b) { return (a [1] b) ? a : b; } for (int [2] = 1; [2] <= n; [2]++) { // loop body }
The max function returns the greater of two values using '>'. The loop variable is commonly 'i' for iterating items.
Fill all three blanks to complete the DP table update inside the nested loops.
for (int i = 1; i <= n; i++) { for (int w = 1; w <= capacity; w++) { if (wt[i - 1] [1] w) { dp[i][w] = max(val[i - 1] + dp[i - 1][w [2] wt[i - 1]], dp[i - 1][w]); } else { dp[i][w] = dp[i - 1][w]; } } }
The condition checks if the item weight is less than or equal to current capacity. The remaining capacity is calculated by subtracting the item's weight. The max function compares two values.