Bird
Raised Fist0
DSA C++programming~10 mins

0 1 Knapsack Problem in DSA C++ - Execution Trace

Choose your learning style10 modes available
Concept Flow - 0 1 Knapsack Problem
Start with empty knapsack
↓
For each item i
↓
For each weight w from 0 to max capacity
↓
Check if item i fits (weight[i
Yes No↓
Include item i: value[i
↓
Take max of include/exclude
↓
Fill dp table
↓
Answer is dp[number_of_items
We fill a table where each cell shows the best value for items up to i and capacity w, choosing to include or exclude the current item.
Execution Sample
DSA C++
int knapsack(int W, int wt[], int val[], int n) {
  int dp[n+1][W+1];
  for (int i = 0; i <= n; i++) {
    for (int w = 0; w <= W; w++) {
      if (i == 0 || w == 0) dp[i][w] = 0;
      else if (wt[i-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];
    }
  }
  return dp[n][W];
}
This code fills a table to find the max value for given items and capacity, deciding to include or exclude each item.
Execution Table
StepOperationItem iWeight wCondition (wt[i-1] <= w)Include ValueExclude Valuedp[i][w]DP Table Row State
1Initialize dp row 000 to 7N/AN/AN/A0[0,0,0,0,0,0,0,0]
2Initialize dp column 010N/AN/AN/A0[0,0,0,0,0,0,0,0]
3Check item 1 (wt=1,val=1)11Yes1 + dp[0][0]=1dp[0][1]=01[0,1,0,0,0,0,0,0]
4Check item 112Yes1 + dp[0][1]=1dp[0][2]=01[0,1,1,0,0,0,0,0]
5Check item 113Yes1 + dp[0][2]=1dp[0][3]=01[0,1,1,1,0,0,0,0]
6Check item 114Yes1 + dp[0][3]=1dp[0][4]=01[0,1,1,1,1,0,0,0]
7Check item 115Yes1 + dp[0][4]=1dp[0][5]=01[0,1,1,1,1,1,0,0]
8Check item 116Yes1 + dp[0][5]=1dp[0][6]=01[0,1,1,1,1,1,1,0]
9Check item 117Yes1 + dp[0][6]=1dp[0][7]=01[0,1,1,1,1,1,1,1]
10Check item 2 (wt=3,val=4)21NoN/Adp[1][1]=11[0,1,1,1,1,1,1,1]
11Check item 222NoN/Adp[1][2]=11[0,1,1,1,1,1,1,1]
12Check item 223Yes4 + dp[1][0]=4dp[1][3]=14[0,1,1,4,1,1,1,1]
13Check item 224Yes4 + dp[1][1]=5dp[1][4]=15[0,1,1,4,5,1,1,1]
14Check item 225Yes4 + dp[1][2]=5dp[1][5]=15[0,1,1,4,5,5,1,1]
15Check item 226Yes4 + dp[1][3]=5dp[1][6]=15[0,1,1,4,5,5,5,1]
16Check item 227Yes4 + dp[1][4]=5dp[1][7]=15[0,1,1,4,5,5,5,5]
17Check item 3 (wt=4,val=5)31NoN/Adp[2][1]=11[0,1,1,4,5,5,5,5]
18Check item 332NoN/Adp[2][2]=11[0,1,1,4,5,5,5,5]
19Check item 333NoN/Adp[2][3]=44[0,1,1,4,5,5,5,5]
20Check item 334Yes5 + dp[2][0]=5dp[2][4]=55[0,1,1,4,5,5,5,5]
21Check item 335Yes5 + dp[2][1]=6dp[2][5]=56[0,1,1,4,5,6,5,5]
22Check item 336Yes5 + dp[2][2]=6dp[2][6]=56[0,1,1,4,5,6,6,5]
23Check item 337Yes5 + dp[2][3]=9dp[2][7]=59[0,1,1,4,5,6,6,9]
💡 All items and weights processed; dp[n][W] = 9 is the max value.
Variable Tracker
VariableStartAfter Step 3After Step 12After Step 23Final
i (item index)01233
w (weight capacity)01377
dp row 0[0,0,0,0,0,0,0,0][0,0,0,0,0,0,0,0][0,0,0,0,0,0,0,0][0,0,0,0,0,0,0,0][0,0,0,0,0,0,0,0]
dp row 1[0,0,0,0,0,0,0,0][0,1,1,1,1,1,1,1][0,1,1,1,1,1,1,1][0,1,1,1,1,1,1,1][0,1,1,1,1,1,1,1]
dp row 2[0,0,0,0,0,0,0,0][0,0,0,0,0,0,0,0][0,1,1,4,5,5,5,5][0,1,1,4,5,5,5,5][0,1,1,4,5,5,5,5]
dp row 3[0,0,0,0,0,0,0,0][0,0,0,0,0,0,0,0][0,0,0,0,0,0,0,0][0,1,1,4,5,6,6,9][0,1,1,4,5,6,6,9]
Key Moments - 3 Insights
Why do we check if the item's weight is less than or equal to the current capacity before including it?
Because if the item is heavier than the current capacity (w), we cannot include it. This is shown in the execution_table rows where condition is 'No' and dp[i][w] equals dp[i-1][w], meaning we skip the item.
Why do we take the maximum of including or excluding the item?
We want the best value possible. Including the item adds its value plus the best value for the remaining capacity. Excluding keeps the previous best. The dp[i][w] cell stores the max of these two, as seen in the execution_table where dp[i][w] is max(include, exclude).
Why do we initialize the first row and column of the dp table with zeros?
The first row (i=0) means no items, so value is zero. The first column (w=0) means zero capacity, so no items can be included. This base case is shown in steps 1 and 2 where dp[i][0] and dp[0][w] are set to 0.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 12, what is the value of dp[2][3]?
A4
B1
C5
D0
💡 Hint
Refer to the 'dp[i][w]' column in execution_table row with Step 12.
At which step does the dp table first show a value greater than 5?
AStep 14
BStep 21
CStep 16
DStep 23
💡 Hint
Check the 'dp[i][w]' column for values > 5 in execution_table rows.
If the weight of item 2 was 4 instead of 3, how would step 12 change?
ANo change, dp[2][3] remains 4
BCondition would be Yes and dp[2][3] would increase
CCondition would be No and dp[2][3] would equal dp[1][3]
Ddp[2][3] would be zero
💡 Hint
Look at the condition column and how weight affects inclusion in execution_table step 12.
Concept Snapshot
0 1 Knapsack Problem:
- Use a 2D dp table dp[n+1][W+1]
- dp[i][w] = max value using first i items with capacity w
- If item i fits (wt[i-1] <= w), choose max(include, exclude)
- Else exclude item
- Answer at dp[n][W]
Full Transcript
The 0 1 Knapsack Problem uses a table to find the best value of items fitting in a knapsack of capacity W. We build a dp table where each cell dp[i][w] shows the max value using first i items and capacity w. For each item and capacity, we check if the item fits. If yes, we decide to include it or not by comparing values. If no, we skip it. The first row and column are zeros because no items or zero capacity means zero value. The final answer is dp[n][W].

Practice

(1/5)
1. What does the 0 1 Knapsack Problem aim to maximize given a set of items with weights and values?
easy
A. The total weight of items without exceeding the value limit
B. The total value of items without exceeding the weight limit
C. The number of items selected regardless of weight
D. The minimum weight of items selected

Solution

  1. Step 1: Understand the problem goal

    The 0 1 Knapsack Problem tries to select items to maximize total value without exceeding the weight capacity.
  2. Step 2: Identify the constraint

    The total weight of selected items must not exceed the given weight limit.
  3. Final Answer:

    The total value of items without exceeding the weight limit -> Option B
  4. Quick Check:

    Maximize value with weight limit = A [OK]
Hint: Maximize value, keep total weight ≤ capacity [OK]
Common Mistakes:
  • Confusing weight limit with value limit
  • Trying to maximize weight instead of value
  • Ignoring the weight constraint
2. Which of the following is the correct way to declare the DP table for the 0 1 Knapsack Problem in C++ if n is number of items and W is max weight?
easy
A. int dp[n+1][W+1];
B. int dp[W+1][n+1];
C. int dp[n][W];
D. int dp[W][n];

Solution

  1. Step 1: Understand DP table dimensions

    The DP table stores solutions for items 0 to n and weights 0 to W, so size is (n+1) x (W+1).
  2. Step 2: Match correct declaration

    int dp[n+1][W+1]; declares dp with dimensions [n+1][W+1], matching the problem requirements.
  3. Final Answer:

    int dp[n+1][W+1]; -> Option A
  4. Quick Check:

    DP table size = (n+1) x (W+1) [OK]
Hint: DP table size = items+1 by weight+1 [OK]
Common Mistakes:
  • Using dp[n][W] misses base case row/column
  • Swapping dimensions incorrectly
  • Declaring smaller arrays causing out-of-bound errors
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

  1. 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.
  2. 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.
  3. Final Answer:

    220 -> Option C
  4. 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

  1. 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.
  2. Step 2: Correct indexing

    Use weights[i-1] and values[i-1] to access correct elements.
  3. Final Answer:

    Indexing weights and values with i instead of i-1 -> Option A
  4. 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?
hard
A. 75
B. 65
C. 70
D. 60

Solution

  1. Step 1: Analyze items and weight limit

    Items: values = {20,5,10,40,15,25}, weights = {1,2,3,8,7,4}, max weight = 10.
  2. Step 2: Find best combination under weight 10

    Choose items with weights 1,3,4 (values 20,10,25) total weight 8, value 55; or items 1,2,6 (weights 1,2,4) value 20+5+25=50; best is items 1,4 (weights 1+8=9) value 20+40=60; or items 4 and 6 (8+4=12 >10) invalid; items 1,5,6 (1+7+4=12 >10) invalid; items 1,3,5 (1+3+7=11 >10) invalid; items 2,3,6 (2+3+4=9) value 5+10+25=40; items 1,2,3,6 (1+2+3+4=10) value 20+5+10+25=60; items 1,2,3,5 (1+2+3+7=13 >10) invalid; items 1,2,3,4 (1+2+3+8=14 >10) invalid; items 1,2,6,5 (1+2+4+7=14 >10) invalid; items 1,3,6 (1+3+4=8) value 20+10+25=55; items 1,2,3,6 total value 60 and weight 10 fits exactly.
  3. Final Answer:

    60 -> Option D
  4. Quick Check:

    Max value with weight 10 = 60 [OK]
Hint: Try combinations fitting weight limit, sum max values [OK]
Common Mistakes:
  • Ignoring weight limit when summing values
  • Missing best combination with multiple items
  • Assuming greedy choice works always
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard