3. What will be the output of the following Rust code snippet for Unbounded Knapsack?
let weights = vec![2, 3, 4];
let values = vec![15, 20, 30];
let capacity = 7;
let mut dp = vec![0; capacity + 1];
for w in 1..=capacity {
for i in 0..weights.len() {
if weights[i] <= w {
dp[w] = dp[w].max(dp[w - weights[i]] + values[i]);
}
}
}
println!("{}", dp[capacity]);
medium
A. 65
B. 50
C. 45
D. 60
Solution
Step 1: Trace DP array updates for capacity 7
Calculate max value for each capacity:
- w=1: no items fit, dp[1]=0
- w=2: use item 0 (weight 2, value 15), dp[2]=15
- w=3: item 1 fits (3,20), dp[3]=20
- w=4: item 2 fits (4,30), dp[4]=30; also dp[4-2]=dp[2]=15 + 15=30, max=30
- w=5: check items:
item0: dp[5-2]=dp[3]=20 +15=35
item1: dp[5-3]=dp[2]=15 +20=35
item2: dp[5-4]=dp[1]=0 +30=30
max=35
- w=6:
item0: dp[6-2]=dp[4]=30 +15=45
item1: dp[6-3]=dp[3]=20 +20=40
item2: dp[6-4]=dp[2]=15 +30=45
max=45
- w=7:
item0: dp[7-2]=dp[5]=35 +15=50
item1: dp[7-3]=dp[4]=30 +20=50
item2: dp[7-4]=dp[3]=20 +30=50
max=50
Step 2: Verify final dp[7]
dp[7] = 50
Final Answer:
50 -> Option B
Quick Check:
Max value at capacity 7 = 50 [OK]
Hint: Check all items for each capacity and pick max value [OK]
Common Mistakes:
Not considering multiple uses of same item
Incorrectly updating dp array
Off-by-one errors in loops
4. Identify the bug in the following Rust code snippet for Unbounded Knapsack and select the correct fix:
let weights = vec![1, 3, 4];
let values = vec![10, 40, 50];
let capacity = 6;
let mut dp = vec![0; capacity];
for w in 1..=capacity {
for i in 0..weights.len() {
if weights[i] <= w {
dp[w] = dp[w].max(dp[w - weights[i]] + values[i]);
}
}
}
println!("{}", dp[capacity]);
medium
A. Initialize dp with size capacity + 1 instead of capacity.
B. Change loop to for w in 0..capacity instead of 1..=capacity.
C. Use dp[w + weights[i]] instead of dp[w - weights[i]].
D. Replace max with min in dp update.
Solution
Step 1: Check dp vector size
dp is initialized with size capacity (6), but indices go up to capacity (6), so dp[6] access is out of bounds.
Step 2: Fix dp size to capacity + 1
Initialize dp with size capacity + 1 to safely access dp[capacity].
Final Answer:
Initialize dp with size capacity + 1 instead of capacity. -> Option A
Quick Check:
dp size = capacity + 1 to avoid index error [OK]
Hint: DP array size must be capacity + 1 for indexing [OK]
Common Mistakes:
Off-by-one error in dp array size
Accessing dp out of bounds
Incorrect loop ranges
5. Given items with weights [1, 3, 4] and values [10, 40, 50], and a knapsack capacity of 7, what is the maximum value achievable using the Unbounded Knapsack approach?