Sub topic 17
Beyond One Constraint: Multidimensional and Related Variants
This chapter assumes you are comfortable with the one-array 0/1 DP and its backwards capacity loop, the pseudo-polynomial running time argument, and the value-indexed DP and FPTAS from earlier chapters. Here the same take-or-skip idea is stretched in two directions. First, an item can consume more than one resource. Second, the rules about which items may be combined can change.
When One Capacity Is Not Enough
Real packing problems rarely have a single limit. A delivery van has a weight limit and a volume limit. A cloud scheduler has CPU, memory and disk budgets. A project portfolio has money and staff hours. The multidimensional knapsack problem (also called the d-dimensional or multi-constraint knapsack) gives each item a value and a vector of d weights. You must choose a subset so that every one of the d capacities is respected and the total value is as large as possible.
The recurrence keeps its shape. The state just gains one coordinate per resource:
best(i, c1, c2, ..., cd)is the best value using itemsi..n-1with remaining capacitiesc1..cd.- Skip item
i:best(i+1, c1, ..., cd). - Take item
i, if everywk[i] <= ck:value[i] + best(i+1, c1 - w1[i], ..., cd - wd[i]).
Two-Dimensional DP in Code
With two resources, weight and volume, the one-array trick becomes a two-dimensional array indexed by remaining weight and remaining volume. Both loops run backwards, for the same reason as before: each cell must read values from the previous item's layer, not the current one.
def knapsack_2d(values, weights, volumes, max_weight, max_volume):
# dp[c][d] = best value with weight budget c and volume budget d
dp = [[0] * (max_volume + 1) for _ in range(max_weight + 1)]
for val, w, vol in zip(values, weights, volumes):
for c in range(max_weight, w - 1, -1):
for d in range(max_volume, vol - 1, -1):
candidate = dp[c - w][d - vol] + val
if candidate > dp[c][d]:
dp[c][d] = candidate
return dp[max_weight][max_volume]
values = [60, 100, 120]
weights = [10, 20, 30]
volumes = [4, 5, 2]
print(knapsack_2d(values, weights, volumes, 50, 6)) # 180The weight-only answer for these items is 220, from items 1 and 2. That pair needs volume 7, so the volume limit of 6 rules it out. The best feasible set is items 0 and 2: weight 40, volume 6, value 180.
What the Extra Dimensions Cost
The table has one axis per resource, so time is O(n · C1 · C2 · ... · Cd) and space is O(C1 · ... · Cd). With d = 3 and each capacity at 1,000, the array has a billion cells before you even multiply by n. The pseudo-polynomial bound from the single-constraint case gets worse with every resource you add.
Approximation also gets harder. The single-constraint problem has an FPTAS. For d ≥ 2, no FPTAS exists unless P = NP. A PTAS still exists for any fixed d, but its running time grows very fast as the accuracy improves, so it is mostly of theoretical interest.
The greedy intuition breaks too. Value per unit of weight is a single ratio, but with two resources you cannot rank items by one number. An item can be cheap in weight and expensive in volume. The fractional (LP) relaxation is still a valid upper bound for branch and bound. Solving it now takes a linear programming solver, because sorting by a ratio no longer works.
Practical Approaches for Large Instances
| Situation | Approach | Why |
|---|---|---|
| d = 2, small capacities | Multi-dimensional DP as above | Exact and simple |
| Large capacities, few items | Meet in the middle with dominance filtering | Exponential only in n/2 |
| Moderate n, any d | Integer linear programming solver | LP bounds plus cutting planes prune well |
| Need a quick bound or heuristic | Lagrangian or surrogate relaxation | Folds d constraints into one weighted constraint, then runs 1-D DP |
| Very large n | Greedy by an "effective" ratio, then local search | Fast, no optimality guarantee |
Surrogate relaxation deserves a closer look. Pick non-negative multipliers u1..ud. Replace all constraints with the single constraint sum_k uk · wk[i] summed over chosen items <= sum_k uk · Ck. Any set that is feasible for the original problem is feasible for this one, so the optimum of the one-constraint problem is an upper bound. Its solution may break an original constraint, so you still have to check it and repair it.
Related Variants That Change the Rules
Many problems are the same DP in disguise. The table changes in one of three ways: the initial values, the combining operation, or the loop structure.
Multiple-Choice Knapsack
In the multiple-choice knapsack problem, items are divided into groups and you may take at most one item from each group. An example is choosing one shipping option per package, or one size per product. The DP processes one group at a time. For each capacity, from high to low, it tries every item in the group:
def multiple_choice_knapsack(groups, capacity):
# groups: list of lists of (value, weight); weights > 0
dp = [0] * (capacity + 1)
for group in groups:
for c in range(capacity, -1, -1):
for value, weight in group:
if weight <= c and dp[c - weight] + value > dp[c]:
dp[c] = dp[c - weight] + value
return dp[capacity]
groups = [
[(60, 10), (90, 25)],
[(100, 20), (130, 30)],
[(120, 35)],
]
print(multiple_choice_knapsack(groups, 50)) # 190This works because dp[c - weight] has a smaller index than c and has not been updated for the current group yet, so it still holds the result from earlier groups only. The answer, 190, comes from either (60, 10) with (130, 30), or (90, 25) with (100, 20).
Exact Fill, Covering and Counting
| Variant | Change to the 0/1 DP | Initial array |
|---|---|---|
| Subset sum (can we hit exactly W?) | Store booleans, combine with `or` | `[True] + [False] * W` |
| Exact-capacity maximum value | Same `max` update | `[0] + [-inf] * W` |
| Minimum cost to reach at least W | Use `min`, clamp index at W | `[0] + [inf] * W` |
| Count subsets with sum W | Combine with `+` | `[1] + [0] * W` |
| Multiple knapsacks (several bags) | State per bag; NP-hard in the strong sense | Usually solved by ILP |
The exact-capacity row is a common source of bugs. If you start every cell at 0, dp[c] means "best value with weight at most c". To force an exact fill, mark unreachable capacities as -inf. Then only sums actually built from item weights can win.
def exact_fill_max_value(values, weights, capacity):
NEG = float('-inf')
dp = [0] + [NEG] * capacity
for v, w in zip(values, weights):
for c in range(capacity, w - 1, -1):
if dp[c - w] + v > dp[c]:
dp[c] = dp[c - w] + v
return dp[capacity] if dp[capacity] != NEG else None
print(exact_fill_max_value([60, 100, 120], [10, 20, 30], 50)) # 220
print(exact_fill_max_value([60, 100, 120], [10, 20, 30], 45)) # NoneVariants That Leave DP Behind
Some variants keep the name but lose the structure that makes DP work. In the quadratic knapsack problem, pairs of items earn extra value when both are chosen. The value of taking item i then depends on which earlier items were taken, so remaining capacity alone is no longer enough state. Knapsack with conflict graphs (some pairs forbidden) has the same problem. For these, branch and bound, ILP solvers or heuristics are the usual tools.
Exercise
A van has weight limit 8 and volume limit 5. Items as (value, weight, volume): A = (10, 5, 1), B = (7, 3, 3), C = (8, 4, 2), D = (6, 2, 3). What is the best total value, and which items achieve it?
Show answer
18, from A and C (weight 9 is too much, so check again) — A and C weigh 9, which exceeds 8, so it is infeasible. Checking the feasible pairs: A+B = 17 (weight 8, volume 4), A+D = 16 (weight 7, volume 4), B+C = 15 (weight 7, volume 5), C+D = 14 (weight 6, volume 5), B+D needs volume 6 and is infeasible. No triple fits within weight 8 and volume 5. The answer is 17 with items A and B.
Exercise
In multiplechoiceknapsack, a teammate moves "for value, weight in group" outside "for c in range(capacity, -1, -1)". On groups [[(5, 2), (6, 3)]] with capacity 5, what does the buggy version return, and what is the correct answer?
Show answer
The buggy version runs a 0/1 pass per item, so both items in the group can be taken: weight 5, value 11. The correct answer allows at most one item from the group, so it is 6.
Exercise
Why can't you get an FPTAS for two-dimensional knapsack by scaling values and running a value-indexed DP, the way the single-constraint FPTAS does?
Show answer
The value-indexed DP stores, for each value, the minimum weight that reaches it. With two resources, there is no single "minimum" to store, because one partial solution can use less weight while another uses less volume, and neither dominates. You would have to keep a set of non-dominated (weight, volume) pairs per value, and that set can grow exponentially. This matches the result that no FPTAS exists for d ≥ 2 unless P = NP.