📖 Scenario: You are packing a backpack for a hiking trip. You have several items, each with a weight and a value. Your backpack can only carry a limited weight. You want to choose items to maximize the total value without exceeding the weight limit.
🎯 Goal: Build a Java program that uses the 0 1 Knapsack algorithm to find the best combination of items to maximize value within the weight limit.
📋 What You'll Learn
Create arrays for item weights and values
Create an integer variable for the maximum weight capacity
Implement the 0 1 Knapsack dynamic programming solution
Print the maximum value that fits in the backpack
💡 Why This Matters
🌍 Real World
Packing efficiently for trips, resource allocation, budget management, and many optimization problems in logistics.
💼 Career
Understanding dynamic programming and optimization problems is essential for software engineers, data scientists, and algorithm developers.
Progress0 / 4 steps
1
Create item weights and values arrays
Create two integer arrays called weights and values with these exact values: weights = {2, 3, 4, 5} and values = {3, 4, 5, 6}.
DSA Java
Hint
Use array syntax with exact values for weights and values.
2
Set the maximum weight capacity
Create an integer variable called maxWeight and set it to 5.
DSA Java
Hint
Use an integer variable named maxWeight and assign 5.
3
Implement the 0 1 Knapsack dynamic programming solution
Create a 2D integer array called dp with size (weights.length + 1) by (maxWeight + 1). Use nested for loops with variables i and w to fill dp using the 0 1 Knapsack logic: if the current item weight is less than or equal to w, set dp[i][w] to the maximum of including or excluding the item; otherwise, copy the value from above.
DSA Java
Hint
Use two loops: outer for items (i), inner for weights (w). Use Math.max to choose best value.
4
Print the maximum value that fits in the backpack
Print the value stored in dp[weights.length][maxWeight] using System.out.println.
DSA Java
Hint
Print the last cell of dp array which holds the maximum value.
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 value of items without exceeding the weight limit
B. The total weight of items regardless of value
C. The number of items selected
D. The minimum weight of selected items
Solution
Step 1: Understand the problem goal
The 0 1 Knapsack Problem tries to select items to maximize total value without exceeding the weight capacity.
Step 2: Identify the constraint
The total weight of selected items must not exceed the knapsack's capacity.
Final Answer:
The total value of items without exceeding the weight limit -> Option A
Quick Check:
Maximize value under weight limit = The total value of items without exceeding the weight limit [OK]
Hint: Focus on maximizing value, not weight or count [OK]
Common Mistakes:
Confusing weight maximization with value maximization
Ignoring the weight limit constraint
Thinking the problem counts items instead of values
2. Which of the following is the correct way to declare the DP array for the 0 1 Knapsack Problem in Java?
easy
A. int[] dp = new int[n+1];
B. int[][] dp = new int[n+1][W+1];
C. int[][] dp = new int[W+1][n+1];
D. int dp = new int[n+1][W+1];
Solution
Step 1: Understand DP array dimensions
We use a 2D array with rows for items (n+1) and columns for weight capacities (W+1).
Step 2: Check Java syntax for 2D array
Correct syntax is int[][] dp = new int[n+1][W+1];
Final Answer:
int[][] dp = new int[n+1][W+1]; -> Option B
Quick Check:
2D array with items and weights = int[][] dp = new int[n+1][W+1]; [OK]
Hint: Trace DP table row by row for each item [OK]
Common Mistakes:
Adding values without checking weight limit
Confusing indices in arrays
Forgetting to consider previous dp values
4. Identify the error in this Java code snippet for 0 1 Knapsack and select the fix:
int[] weights = {2, 3, 4};
int[] values = {3, 4, 5};
int capacity = 5;
int n = weights.length;
int[][] dp = new int[n][capacity+1];
for (int i = 1; i <= n; i++) {
for (int w = 1; w <= capacity; w++) {
if (weights[i-1] <= w) {
dp[i][w] = Math.max(values[i-1] + dp[i-1][w - weights[i-1]], dp[i-1][w]);
} else {
dp[i][w] = dp[i-1][w];
}
}
}
medium
A. Change dp array size to int[n+1][capacity+1]
B. Change loop to start from i = 0
C. Use dp[i][w-1] instead of dp[i-1][w]
D. Remove the if condition inside the loop
Solution
Step 1: Check dp array size and indexing
dp is declared as int[n][capacity+1], but loops use i from 1 to n, accessing dp[i], which causes ArrayIndexOutOfBoundsException.
Step 2: Fix dp size to match loop indices
Declare dp as int[n+1][capacity+1] to allow indexing from 0 to n safely.
Final Answer:
Change dp array size to int[n+1][capacity+1] -> Option A
Quick Check:
Array size must match loop indices [OK]
Hint: DP size = items+1 rows to avoid index errors [OK]
Common Mistakes:
Using dp size smaller than loop range
Starting loop from 0 but indexing from 1
Ignoring array index exceptions
5. Given items with weights = {2, 3, 5, 7}, values = {1, 5, 2, 4}, and capacity = 10, what is the maximum value achievable using 0 1 Knapsack? Also, which items are selected?
hard
A. Maximum value 6; items with weights 7 and 2 selected
B. Maximum value 7; items with weights 2, 3, and 5 selected
C. Maximum value 9; items with weights 3, 5, and 2 selected
D. Maximum value 9; items with weights 3 and 7 selected
Solution
Step 1: Calculate maximum value using DP
Check combinations:
- Items 3 and 7 weights sum to 10, values 5 + 4 = 9 (3 weight item value is 5, 7 weight item value is 4)
- Items 2,3,5 weights sum to 10, values 1+5+2=8
- Items 3 and 7 give 9 value, better than others
- Items 2 and 7 sum weight 9, values 1+4=5
Maximum value is 9 with items 3 and 7.
Step 2: Verify selected items
Selected items are weights 3 and 7 with values 5 and 4 respectively.
Final Answer:
Maximum value 9; items with weights 3 and 7 selected -> Option D
Quick Check:
Max value 9 with weights 3+7 = 10 capacity [OK]
Hint: Check all combinations fitting capacity for max value [OK]
Common Mistakes:
Adding values without checking total weight
Selecting items exceeding capacity
Confusing item weights and values
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.