3. What is the output of the following C++ code snippet for 0 1 Knapsack Problem?
int values[] = {60, 100, 120};
int weights[] = {10, 20, 30};
int W = 50;
int n = 3;
int dp[4][51] = {0};
for (int i = 1; i <= n; i++) {
for (int w = 1; w <= W; w++) {
if (weights[i-1] <= w) {
dp[i][w] = std::max(dp[i-1][w], dp[i-1][w - weights[i-1]] + values[i-1]);
} else {
dp[i][w] = dp[i-1][w];
}
}
}
std::cout << dp[n][W] << std::endl;
medium
A. 160
B. 180
C. 220
D. 250
Solution
Step 1: Understand the DP logic
The code fills dp table to find max value for weight limit 50 with items of given weights and values.
Step 2: Calculate max value manually
Items: (10,60), (20,100), (30,120). Max value for weight 50 is choosing items 2 and 3: 100 + 120 = 220.
Final Answer:
220 -> Option C
Quick Check:
Max value for W=50 = 220 [OK]
Hint: Pick items with max value under weight limit [OK]
Common Mistakes:
Adding weights instead of values
Choosing items exceeding weight limit
Misindexing arrays causing wrong dp values
4. Identify the bug in this 0 1 Knapsack DP code snippet:
for (int i = 1; i <= n; i++) {
for (int w = 1; w <= W; w++) {
if (weights[i] <= w) {
dp[i][w] = std::max(dp[i-1][w], dp[i-1][w - weights[i]] + values[i]);
} else {
dp[i][w] = dp[i-1][w];
}
}
}
medium
A. Indexing weights and values with i instead of i-1
B. Loop ranges should start from 0 instead of 1
C. Using std::max instead of a custom max function
D. Not initializing dp array to zero
Solution
Step 1: Check array indexing
Arrays weights and values are zero-indexed, but code uses i which starts at 1, causing out-of-bound or wrong access.
Step 2: Correct indexing
Use weights[i-1] and values[i-1] to access correct elements.
Final Answer:
Indexing weights and values with i instead of i-1 -> Option A
Quick Check:
Zero-based arrays need i-1 index [OK]
Hint: Use i-1 for zero-based arrays in loops starting at 1 [OK]
Common Mistakes:
Accessing arrays with wrong index causing runtime errors
Starting loops at 0 but using i-1 indexing
Ignoring dp initialization
5. Given items with values {20, 5, 10, 40, 15, 25} and weights {1, 2, 3, 8, 7, 4}, and max weight 10, what is the maximum value achievable using 0 1 Knapsack?