Sub topic 11
Bounded Knapsack: Limited Copies and Binary Splitting
This chapter assumes you have read the earlier chapters on the one-dimensional 0/1 DP and on unbounded knapsack. You should know why the capacity loop runs backwards for 0/1 items and forwards for unlimited reuse. It also assumes basic Python and Big-O notation.
The Problem Statement
In the bounded knapsack problem, item i has value v[i], weight w[i] and a count k[i], which is the number of identical copies available. You choose an integer x[i] with 0 <= x[i] <= k[i] for each item. The goal is to maximize the total value sum(x[i] * v[i]) while keeping the total weight sum(x[i] * w[i]) <= W.
The bounded problem sits between the two variants you already know:
| Variant | Allowed copies of item i | Inner loop direction (1D DP) |
|---|---|---|
| 0/1 | 0 or 1 | backwards |
| Bounded | 0 to k[i] | depends on the technique |
| Unbounded | any number | forwards |
Neither loop direction solves it on its own. A backwards loop allows one copy of each item. A forwards loop allows as many copies as fit, which can be more than k[i].
The Naive Reduction: Expand Every Copy
The simplest fix is to write each copy out as a separate 0/1 item. An item with k = 5 becomes five identical items, and you run the backwards 1D DP on the expanded list. This gives correct answers. The cost is O(W * sum(k[i])), because every copy adds a full pass over the capacity array. If one item has a count of 10,000, that item alone costs 10,000 passes.
The expansion is also redundant. Copies 1 to 5 of the same item are interchangeable, so the DP ends up building the same totals in many different ways.
Binary Splitting
Binary splitting replaces the k copies with bundles of sizes 1, 2, 4, ..., 2^(m-1), plus a remainder r = k - (2^m - 1). Here m is the largest number for which 2^m - 1 <= k. Each bundle becomes one 0/1 item. A bundle of size s has value s * v and weight s * w.
Why every count from 0 to k is reachable
The splitting is correct when two things hold. Every count t from 0 to k must be some subset of the bundles, and no subset may add up to more than k.
- The second condition holds because all the bundles together add up to exactly
k. - If
t <= 2^m - 1, writetin binary. The bits pick out which power-of-two bundles to use. - If
t > 2^m - 1, take the remainder bundler. Thent - rfalls between2^m - randk - r = 2^m - 1. Becauser <= 2^m, the lower end is at least 0, sot - rcan be written in binary with the power-of-two bundles.
This is why you cannot just use powers of two up to the next one above k. For k = 13, the bundles 1, 2, 4, 8 add up to 15, so the DP could take 14 or 15 copies, which breaks the count limit.
Implementation
The splitting function stops doubling once the next power is larger than the copies left. It then emits whatever remains as the final bundle. The resulting items go straight into the backwards 1D DP.
def split_bounded(values, weights, counts):
# Turn an item with k copies into O(log k) 0/1 items
items = []
for v, w, k in zip(values, weights, counts):
p = 1
while k > 0:
take = min(p, k)
items.append((v * take, w * take))
k -= take
p *= 2
return items
def knapsack_01_1d(values, weights, capacity):
dp = [0] * (capacity + 1)
for v, w in zip(values, weights):
for c in range(capacity, w - 1, -1):
dp[c] = max(dp[c], dp[c - w] + v)
return dp[capacity]
def knapsack_bounded(values, weights, counts, capacity):
items = split_bounded(values, weights, counts)
vals = [v for v, _ in items]
wts = [w for _, w in items]
return knapsack_01_1d(vals, wts, capacity)
print(split_bounded([10], [3], [5])) # [(10, 3), (20, 6), (20, 6)]
print(split_bounded([1], [1], [13])) # [(1, 1), (2, 2), (4, 4), (6, 6)]
print(knapsack_bounded([60, 100, 120], [10, 20, 30], [2, 1, 1], 50)) # 240With two copies of the first item, the best choice is both copies plus the third item: value 60 + 60 + 120 = 240 at weight exactly 50. The plain 0/1 answer for the same items is 220.
Cost and Comparison
An item with count k becomes about log2(k) + 1 bundles. The total running time is O(W * sum(log k[i])) and the space is O(W).
| Technique | Time | Notes |
|---|---|---|
| Expand every copy | O(W * sum k[i]) | Simplest; fine for small counts |
| Loop over counts per cell | O(W * sum k[i]) | No expansion, same cost |
| Binary splitting | O(W * sum log k[i]) | Standard choice; reuses 0/1 code |
| Monotone queue by residue | O(n * W) | Optimal, but harder to get right |
The "loop over counts" version keeps one item at a time and tries every legal number of copies at each capacity:
def knapsack_bounded_direct(values, weights, counts, capacity):
dp = [0] * (capacity + 1)
for v, w, k in zip(values, weights, counts):
for c in range(capacity, w - 1, -1):
for j in range(1, min(k, c // w) + 1):
cand = dp[c - j * w] + j * v
if cand > dp[c]:
dp[c] = cand
return dp[capacity]
print(knapsack_bounded_direct([60, 100, 120], [10, 20, 30], [2, 1, 1], 50)) # 240The capacity loop runs backwards here as well. When the loop reaches dp[c], every dp[c - j*w] still holds the value from before this item, so taking j copies counts the item exactly j times. This version is useful as a reference to test against. Binary splitting is usually faster.
The monotone-queue method groups capacities by c mod w and keeps a sliding-window maximum over each group. It removes the log factor. You only need it when sum(log k) is large enough to matter.
Gotchas and Edge Cases
- Counts larger than needed. No more than
W // wcopies of an item can ever fit. Clamp withk = min(k, W // w)before splitting. Ifk * w >= W, the limit never binds, so you can treat the item as unbounded and use the forwards loop for that item only. Different items in the same DP may use different loop directions, because each item's pass is independent. - Zero counts. A count of 0 produces no bundles. The
while k > 0loop handles this case without special code. - Bundles heavier than W. A bundle such as
(6v, 6w)can weigh more than the capacity. The rangerange(capacity, w - 1, -1)is then empty, so the bundle is skipped. That is correct, since no solution can use it. - Zero-weight items. Take every copy of an item with
w = 0andv > 0up front, and leave it out of the DP. This avoids reasoning about a loop that reads and writes the same cell. - Reconstruction. If you track which bundles were chosen, convert them back into a copy count for each original item. Store the original item index along with each bundle so that you can add up the bundle sizes per item.
- Value overflow. Bundle values are
s * v. Python integers do not overflow, but in C++ or Java, use 64-bit integers whenk * vmight exceed about 2 * 10^9.
Testing Against Brute Force
Comparing against an obviously correct solver catches mistakes in the splitting logic, especially in how the remainder is handled.
import random
from itertools import product
def brute_bounded(values, weights, counts, capacity):
best = 0
for xs in product(*[range(k + 1) for k in counts]):
wt = sum(x * w for x, w in zip(xs, weights))
if wt <= capacity:
best = max(best, sum(x * v for x, v in zip(xs, values)))
return best
random.seed(1)
for _ in range(300):
n = random.randint(1, 4)
vals = [random.randint(1, 20) for _ in range(n)]
wts = [random.randint(1, 8) for _ in range(n)]
cnts = [random.randint(0, 6) for _ in range(n)]
cap = random.randint(0, 30)
expected = brute_bounded(vals, wts, cnts, cap)
assert knapsack_bounded(vals, wts, cnts, cap) == expected
assert knapsack_bounded_direct(vals, wts, cnts, cap) == expected
print("all tests passed")Run this in the same file as the earlier code blocks so that knapsack_bounded and knapsack_bounded_direct are defined.
Exercises
Exercise
List the bundles that binary splitting produces for an item with count k = 20, and show how the count 17 is formed from them.
Show answer
The bundles are 1, 2, 4, 8 and a remainder of 5 (since 1+2+4+8 = 15 and 20-15 = 5). The count 17 is formed as 5 + 8 + 4, which leaves 12 = 8 + 4 for the powers of two after the remainder is taken.
Exercise
Why is it wrong to split k = 13 into bundles 1, 2, 4, 8?
Show answer
Those bundles add up to 15, so the DP could select 14 or 15 copies and break the limit of 13. The remainder bundle (6 instead of 8) keeps the total at exactly k while still allowing every count from 0 to 13.
Exercise
An instance has W = 10,000 and 50 items, each with a count of 1,000. Roughly how many inner-loop updates do copy expansion and binary splitting each perform?
Show answer
Copy expansion uses 50 1,000 = 50,000 items, so about 50,000 10,000 = 5 10^8 updates. Binary splitting uses about 10 bundles per item (1, 2, 4, ..., 256 and a remainder of 489), which makes 500 items and about 5 10^6 updates. Splitting does roughly 100 times less work.
Exercise
An item has weight 7 and count 50, and the capacity is 100. What should you do before splitting, and why?
Show answer
Clamp the count to 100 // 7 = 14, because more than 14 copies can never fit. Since 50 * 7 >= 100, you can also treat the item as unbounded and use a forwards capacity loop for it alone, which avoids splitting it at all.