0/1 to Bounded Knapsack Optimization and Traceback
Dynamic ProgrammingModel answerLast updated
Solve the 0/1 knapsack problem with optimal item selection, optimize its space complexity, and extend the solution to bounded knapsacks efficiently.
Given $n$ items, where item $i$ has weight weight[i] and value value[i], and a total knapsack capacity $W$, complete the following tasks:
- Standard 0/1 Knapsack with Traceback: Compute the maximum total value attainable without exceeding total weight $W$. Reconstruct and return one valid set of chosen item indices. Implement this in $\mathcal{O}(nW)$ time and $\mathcal{O}(nW)$ space.
- Space Optimization: Explain how to compute the maximum value in $\mathcal{O}(W)$ auxiliary space. Discuss how item selection can be reconstructed under memory constraints (e.g., using bitsets or Hirschberg's divide-and-conquer approach).
- Bounded Knapsack Extension: Extend the formulation to the case where each item $i$ can be picked up to
count[i]times.- Implement an efficient solution using binary decomposition of item quantities.
- Explain how a sliding window monotonic queue achieves an exact $\mathcal{O}(nW)$ time complexity.
- Dry Run: Trace both algorithms on the following test cases:
- 0/1 Case:
weight = [2, 3, 4],value = [4, 5, 10], $W = 7$. - Bounded Case: Same items and capacity, with
count = [3, 1, 2].
- 0/1 Case:
Hints
Hint 1
For the 1D space optimization in 0/1 knapsack, iterate through capacity values in reverse order to ensure each item is evaluated at most once.
Hint 2
In binary decomposition of count C, break C into powers of 2 (1, 2, 4, ...) plus the remaining count. Expressing any number up to C as a subset sum of these components turns the problem back into 0/1 knapsack.
Hint 3
For bounded knapsack in strict O(nW) time, group capacities by their remainder modulo weight[i] and use a monotonic queue to find the maximum DP value within a sliding window of size count[i].
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. 0/1 Knapsack: 2D Formulation and Item Traceback
DP State & Recurrence
Define dp[i][c] as the maximum value achievable considering a subset of the first i items with a maximum weight capacity of c.
- Base Case:
dp[0][c] = 0for all $0 \le c \le W$. - Transition: $$\text{dp}[i][c] = \begin{cases} \text{dp}[i-1][c] & \text{if } w_i > c \ \max(\text{dp}[i-1][c], \text{dp}[i-1][c - w_i] + v_i) & \text{if } w_i \le c \end{cases}$$
Reconstruction
To identify the indices of the selected items, start from state $(n, W)$ and step backward:
- If
dp[i][c] != dp[i - 1][c], then item $i-1$ was included. Record index $i-1$ and reduce capacity $c \leftarrow c - \text{weight}[i-1]$. - Otherwise, item $i-1$ was omitted, so capacity $c$ remains unchanged.
2. Space Optimization & Trade-Offs
$\mathcal{O}(W)$ Space Optimization
Since computing row i only requires values from row i - 1, we can compress the table into a single 1D array of size $W + 1$.
To ensure that each item is used at most once, the capacity loop must run in descending order (from $W$ down to $\text{weight}[i]$). Traversing in reverse prevents an item's updated DP value at capacity $c - w$ from overwriting the previous row's state before capacity $c$ reads it.
Reconstructing Items in Restricted Memory
- Bitmask Matrix ($\mathcal{O}(nW)$ bits): Maintain a boolean or bitset array
taken[i][c]indicating whether itemiwas selected at capacityc. This retains the $\mathcal{O}(nW)$ space complexity structural bound, but reduces space consumption by a factor of 32 or 64. - Hirschberg's Divide and Conquer ($\mathcal{O}(W)$ Space, $\mathcal{O}(nW)$ Time):
- Split items into two equal halves.
- Run forward DP on the left half and backward DP on the right half to find DP rows $L$ and $R$.
- Find split capacity $s \in [0, W]$ that maximizes $L[s] + R[W - s]$.
- Recurse on the left half with capacity $s$ and right half with capacity $W - s$.
- Total runtime is $nW + \frac{nW}{2} + \frac{nW}{4} + \dots = 2nW = \mathcal{O}(nW)$ time while maintaining strict $\mathcal{O}(W)$ space.
3. Bounded Knapsack Extension
When item $i$ has a count constraint $C_i$:
Approach A: Binary Decomposition
Instead of adding $C_i$ identical copies of item $i$ individually (which yields $\mathcal{O}(W \sum C_i)$ time), split count $C_i$ into powers of two: $$1, 2, 4, 8, \dots, 2^k, R$$ where $R = C_i - (2^{k+1} - 1)$ is the remainder.
Any integer in $[0, C_i]$ can be uniquely represented as a combination of these transformed items. This reduces the effective number of items to $\sum \lfloor \log_2 C_i \rfloor$, resulting in a complexity of $\mathcal{O}(W \sum \log C_i)$.
Approach B: Monotonic Queue ($\mathcal{O}(nW)$ Strict Time)
For item $i$ with weight $w$, value $v$, and count $c$, group capacities by remainder $r = j \pmod w$. For a fixed remainder $r$, let $j = r + k \cdot w$. The recurrence takes the form: $$\text{dp}{\text{new}}[r + k \cdot w] = \max{k - c \le t \le k} \left( \text{dp}_{\text{old}}[r + t \cdot w] + (k - t)v \right)$$
Rewriting the maximized term: $$\text{dp}{\text{new}}[r + k \cdot w] = k \cdot v + \max{k - c \le t \le k} \left( \text{dp}_{\text{old}}[r + t \cdot w] - t \cdot v \right)$$
This is a standard sliding window maximum over window size $c + 1$. A monotonically decreasing queue can maintain the maximum value of $(\text{dp}_{\text{old}}[r + t \cdot w] - t \cdot v)$ in amortized $\mathcal{O}(1)$ time per state, yielding a total time complexity of $\mathcal{O}(nW)$ and space complexity of $\mathcal{O}(W)$.
4. Implementation (Python)
from collections import deque
def knapsack_01_2d(weight, value, W):
"""0/1 Knapsack with full 2D DP table and item traceback.
Time: O(nW), Space: O(nW)
"""
n = len(weight)
dp = [[0] * (W + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
w, v = weight[i - 1], value[i - 1]
for c in range(W + 1):
dp[i][c] = dp[i - 1][c]
if c >= w:
dp[i][c] = max(dp[i][c], dp[i - 1][c - w] + v)
# Traceback optimal items
chosen_items = []
c = W
for i in range(n, 0, -1):
if dp[i][c] != dp[i - 1][c]:
chosen_items.append(i - 1)
c -= weight[i - 1]
chosen_items.reverse()
return dp[n][W], chosen_items
def bounded_knapsack_binary(weight, value, count, W):
"""Bounded Knapsack using Binary Decomposition.
Time: O(W * sum(log(count_i))), Space: O(W)
"""
# Create transformed 0/1 items
packed_items = [] # tuples of (weight, value, original_index, quantity)
for idx, (w, v, c) in enumerate(zip(weight, value, count)):
k = 1
while c > 0:
take = min(k, c)
packed_items.append((w * take, v * take, idx, take))
c -= take
k *= 2
dp = [0] * (W + 1)
# Track item choices for traceback: bit-matrix representation
item_used = [[False] * (W + 1) for _ in range(len(packed_items))]
for p_idx, (w, v, orig_idx, qty) in enumerate(packed_items):
for c in range(W, w - 1, -1):
if dp[c - w] + v > dp[c]:
dp[c] = dp[c - w] + v
item_used[p_idx][c] = True
# Reconstruction of item frequencies
item_counts = [0] * len(weight)
c = W
for p_idx in range(len(packed_items) - 1, -1, -1):
if item_used[p_idx][c]:
w, v, orig_idx, qty = packed_items[p_idx]
item_counts[orig_idx] += qty
c -= w
return dp[W], item_counts
def bounded_knapsack_monoqueue(weight, value, count, W):
"""Bounded Knapsack using Monotonic Queue DP.
Time: O(nW), Space: O(W)
"""
dp = [0] * (W + 1)
for w, v, c in zip(weight, value, count):
if w == 0 or c == 0:
continue
dp_prev = dp[:]
for r in range(w):
mq = deque() # stores tuples: (k_index, val)
for k in range((W - r) // w + 1):
cap = r + k * w
current_val = dp_prev[cap] - k * v
# Maintain monotonic decreasing queue
while mq and mq[-1][1] <= current_val:
mq.pop()
mq.append((k, current_val))
# Remove elements out of window [k - c, k]
if mq[0][0] < k - c:
mq.popleft()
dp[cap] = mq[0][1] + k * v
return dp[W]
5. Dry-Run Traces
Trace 1: 0/1 Knapsack
- Inputs:
weight = [2, 3, 4],value = [4, 5, 10], $W = 7$
| State / Capacity $c$ | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| Initial | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| After Item 0 (w=2, v=4) | 0 | 0 | 4 | 4 | 4 | 4 | 4 | 4 |
| After Item 1 (w=3, v=5) | 0 | 0 | 4 | 5 | 5 | 9 | 9 | 9 |
| After Item 2 (w=4, v=10) | 0 | 0 | 4 | 5 | 10 | 10 | 14 | 15 |
- Traceback from
dp[3][7] = 15:dp[3][7](15) $\neq$dp[2][7](9) $\implies$ Select Item 2 (w=4, v=10). Remaining capacity $c = 7 - 4 = 3$.dp[2][3](5) $\neq$dp[1][3](4) $\implies$ Select Item 1 (w=3, v=5). Remaining capacity $c = 3 - 3 = 0$.dp[1][0](0) $==$dp[0][0](0) $\implies$ Item 0 omitted.
- Result: Max value = 15, Selected indices =
[1, 2].
Trace 2: Bounded Knapsack
- Inputs:
weight = [2, 3, 4],value = [4, 5, 10],count = [3, 1, 2], $W = 7$ - Binary Decomposition:
- Item 0 (w=2, v=4, c=3) $\rightarrow$ decomposed to (w=2, v=4) [qty 1] and (w=4, v=8) [qty 2].
- Item 1 (w=3, v=5, c=1) $\rightarrow$ decomposed to (w=3, v=5) [qty 1].
- Item 2 (w=4, v=10, c=2) $\rightarrow$ decomposed to (w=4, v=10) [qty 1] and (w=4, v=10) [qty 1].
| Transformed Piece | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| Initial | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| (w=2, v=4) | 0 | 0 | 4 | 4 | 4 | 4 | 4 | 4 |
| (w=4, v=8) | 0 | 0 | 4 | 4 | 8 | 8 | 12 | 12 |
| (w=3, v=5) | 0 | 0 | 4 | 5 | 8 | 9 | 12 | 13 |
| (w=4, v=10) | 0 | 0 | 4 | 5 | 10 | 10 | 14 | 15 |
| (w=4, v=10) | 0 | 0 | 4 | 5 | 10 | 10 | 14 | 15 |
- Result: Max value = 15 (achieved by picking Item 1 once and Item 2 once, total weight $3 + 4 = 7$).
6. Complexity Summary
| Algorithm Variant | Time Complexity | Space Complexity |
|---|---|---|
| 0/1 Knapsack (2D Table) | $\mathcal{O}(nW)$ | $\mathcal{O}(nW)$ |
| 0/1 Knapsack (1D Optimized) | $\mathcal{O}(nW)$ | $\mathcal{O}(W)$ |
| 0/1 Knapsack (Hirschberg Traceback) | $\mathcal{O}(nW)$ | $\mathcal{O}(W)$ |
| Bounded Knapsack (Binary Split) | $\mathcal{O}(W \sum \log C_i)$ | $\mathcal{O}(W)$ |
| Bounded Knapsack (Monotonic Queue) | $\mathcal{O}(nW)$ | $\mathcal{O}(W)$ |