Sub topic 13
Indexing by Value When Weights Are Large
The weight-indexed table from earlier chapters takes O(nW) time, where W is the capacity. That is fine when W is a few thousand. It stops working when weights are measured in bytes, grams or cents and W reaches 10^9. Many such instances still have small values: scores from 1 to 100, priority levels, or counts. In that case you can swap the roles of value and weight and build a table whose size depends on the total value instead of the capacity.
This chapter assumes you know the 0/1 recurrence, the bottom-up table, the one-array version with its backwards loop, and why O(nW) is pseudo-polynomial.
Swapping What the Table Measures
The weight-indexed DP answers the question "what is the most value I can get using at most c units of weight?" The value-indexed DP asks the reverse question:
dp[t]is the minimum total weight needed to collect value exactly t.
If no subset has value exactly t, dp[t] is infinity. Once the table is full, the answer is the largest t whose minimum weight fits:
- answer = max { t : dp[t] ≤ W }
The recurrence keeps the same take-or-skip shape. Only the operation changes from max to min:
- dpi[t] = min( dp{i-1}[t], dp{i-1}[t − vi] + wi ) when t ≥ vi
- base case: dp0[0] = 0, and dp0[t] = ∞ for t > 0
The table has V + 1 columns, where V is the sum of all values. Running time is O(nV) and memory is O(V) with one array. The capacity W never sets a table dimension. It only appears in the final comparison, so W can be as large as you like.
The One-Array Implementation
The value-indexed version uses the same one-array trick as before. Each item may be used once, so the inner loop over t runs backwards. That way dp[t - v] still holds the value from before the current item was considered.
def knapsack_by_value(values, weights, capacity):
total = sum(values)
INF = float('inf')
dp = [0] + [INF] * total # dp[t] = min weight to reach value exactly t
for v, w in zip(values, weights):
for t in range(total, v - 1, -1):
if dp[t - v] + w < dp[t]:
dp[t] = dp[t - v] + w
return max(t for t in range(total + 1) if dp[t] <= capacity)
print(knapsack_by_value([60, 100, 120], [10, 20, 30], 50)) # 220The table here has 281 cells. A weight-indexed table for the same input has 51 cells, so the weight-indexed DP is the better choice for this input. The situation flips when you multiply every weight by 10^8. The weight-indexed table would then need 5 × 10^9 cells, while the value-indexed table still has 281.
The max(...) at the end always finds at least one t, because dp[0] = 0 and every capacity is at least 0.
Recovering the Chosen Items
To recover the items, keep the full two-dimensional table and walk back from the answer cell. This works the same way as reconstruction in the weight-indexed table. If row i differs from row i − 1 at the current t, then item i − 1 was taken, so subtract its value and move up a row.
def knapsack_by_value_items(values, weights, capacity):
n = len(values)
total = sum(values)
INF = float('inf')
dp = [[INF] * (total + 1) for _ in range(n + 1)]
dp[0][0] = 0
for i in range(1, n + 1):
v, w = values[i - 1], weights[i - 1]
for t in range(total + 1):
dp[i][t] = dp[i - 1][t]
if t >= v and dp[i - 1][t - v] + w < dp[i][t]:
dp[i][t] = dp[i - 1][t - v] + w
best = max(t for t in range(total + 1) if dp[n][t] <= capacity)
chosen = []
t = best
for i in range(n, 0, -1):
if dp[i][t] != dp[i - 1][t]:
chosen.append(i - 1)
t -= values[i - 1]
chosen.reverse()
return best, chosen
big = 10**9
print(knapsack_by_value_items([60, 100, 120], [big, 2 * big, 3 * big], 5 * big))
# (220, [1, 2])The weights in this example are around 10^9, and the table still has only 4 × 281 cells.
Checking It Against Brute Force
A small randomized test catches most off-by-one and initialization bugs. The script below compares the one-array version with exhaustive search on random small instances.
import random
from itertools import combinations
def knapsack_by_value(values, weights, capacity):
total = sum(values)
INF = float('inf')
dp = [0] + [INF] * total
for v, w in zip(values, weights):
for t in range(total, v - 1, -1):
if dp[t - v] + w < dp[t]:
dp[t] = dp[t - v] + w
return max(t for t in range(total + 1) if dp[t] <= capacity)
def brute(values, weights, capacity):
n = len(values)
best = 0
for r in range(n + 1):
for combo in combinations(range(n), r):
if sum(weights[i] for i in combo) <= capacity:
best = max(best, sum(values[i] for i in combo))
return best
for _ in range(2000):
n = random.randint(0, 7)
values = [random.randint(0, 20) for _ in range(n)]
weights = [random.randint(1, 10**9) for _ in range(n)]
capacity = random.randint(0, 3 * 10**9)
assert knapsack_by_value(values, weights, capacity) == brute(values, weights, capacity)
print("all tests passed")The test includes empty item lists, zero values and capacity 0. All three cases are handled correctly.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Initializing the whole array to 0 | Every value looks reachable at weight 0, so the answer becomes V | Use 0 only at index 0 and infinity everywhere else |
| Looping t forwards | Items get reused, which solves the unbounded variant | Loop from `total` down to `v` |
| Returning `dp[total]` | Returns a weight instead of a value | Return the largest t with `dp[t] <= capacity` |
| Using `max` instead of `min` in the update | Stores the heaviest way to reach each value | The table stores minimum weight, so use `min` |
| Sizing the table by n × max value but summing wrong | Index out of range | Use `sum(values)` as the bound, or any proven upper bound on the optimum |
Edge Cases and Small Improvements
- Common divisor of values. If every value is a multiple of g, divide the values by g, solve, then multiply the answer by g. This shrinks the table by a factor of g. The same trick works for the weight-indexed DP: divide the weights by g and use the floor of W / g as the capacity.
- Items heavier than W. Drop them before building the table. They can never be taken, and removing them lowers V.
- Tighter bound on V. The answer never exceeds the fractional-greedy optimum, so you can size the table by that bound instead of the full sum.
- Unbounded variant. Running the t loop forwards lets each item be reused, just as in the weight-indexed case. The total-value bound no longer holds when items repeat, so bound t by the greedy fractional value instead.
Choosing Between the Two Tables
Both versions are pseudo-polynomial. Neither escapes NP-hardness. They differ only in which number appears in the running time, so estimate both products before you write any code.
| Situation | Better choice | Cost |
|---|---|---|
| W small, values large or real-valued | Weight-indexed | O(nW) |
| W huge, values small integers | Value-indexed | O(nV) |
| Both W and V huge, n small (about 40) | Neither; see meet in the middle | O(2^(n/2) · n) |
| Both huge, n large, near-optimal acceptable | Scale the values, then use the value-indexed DP | Covered in the FPTAS chapter |
Value indexing needs integer values. Weights can be any non-negative numbers, including floats, because they are only added and compared. Weight indexing has the opposite requirement. So if your weights are real numbers and your values are integers, the value-indexed DP is the only exact DP of the two.
This is the property the approximation scheme in a later chapter builds on. When values are too large, rounding them down to a coarser scale makes V small enough for the value-indexed table. The cost is a bounded loss in solution quality.
Exercise
You have n = 200 items with weights up to 10^12 and values between 1 and 50, and capacity W = 5 × 10^13. Estimate the table size for the weight-indexed and value-indexed DPs and say which one you would use.
Show answer
The weight-indexed DP needs about n × W = 200 × 5 × 10^13 = 10^16 cell updates, which is infeasible. The total value is at most 200 × 50 = 10,000, so the value-indexed DP needs about 200 × 10,001 ≈ 2 × 10^6 updates and an array of 10,001 entries. Use the value-indexed DP.
Exercise
A colleague writes dp = [0] * (total + 1) instead of [0] + [INF] * total in knapsackbyvalue. What does the function return for values [60, 100, 120], weights [10, 20, 30], capacity 50, and why?
Show answer
It returns 280. With every entry starting at 0, every value t looks reachable with weight at most 0, and the updates only ever lower entries further. So all entries stay at 0, every t passes the dp[t] <= capacity test, and the maximum t is the total value, 280.
Exercise
Values are [30, 45, 75] and weights are [4, 5, 9] with capacity 10. Use the common-divisor trick to shrink the value-indexed table, then give the optimal value.
Show answer
All values are multiples of 15, so solve with values [2, 3, 5] and V = 10 instead of 150. The feasible subsets are {0, 1} with weight 9 and scaled value 5, and {2} with weight 9 and scaled value 5. Every other subset with more than one item exceeds capacity 10. The scaled optimum is 5, so the true optimum is 5 × 15 = 75.