Sub topic 13
Indexing by Value When Weights Are Large
This chapter assumes you know the one-dimensional 0/1 DP with its backwards capacity loop, and that you know why O(nW) counts as pseudo-polynomial. The idea here is to swap which quantity the table is indexed by.
The problem with large capacities
The weight-indexed DP uses an array with W + 1 cells, where W is the capacity. That works well when W is a few thousand. Suppose instead the weights are measured in grams and the capacity is 3,000,000,000. The array would need three billion entries, even if there are only five items.
Often the values are small even when the weights are huge. Prices in whole dollars or scores from 1 to 100 are typical examples. In those cases, index the table by value instead.
Flipping the state
The weight-indexed table answers this question: "with capacity c, what is the most value I can get?" The value-indexed table answers the reverse question:
dp[t]is the minimum total weight needed to reach a total value of exactlyt.
Let V be the sum of all values. The array has V + 1 cells. dp[0] = 0, and every other cell starts at infinity, meaning "not reachable yet." For each item (v, w), the update is:
dp[t] = min(dp[t], dp[t - v] + w)
The loop over t runs backwards for the same reason as in the 0/1 weight-indexed version: each item can be used at most once. When the table is finished, the answer is the largest t with dp[t] <= capacity.
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 final max always finds at least one value, because dp[0] = 0 fits in any capacity of zero or more.
Cost comparison
| Version | Table size | Time | Good when |
|---|---|---|---|
| Indexed by weight | W + 1 | O(nW) | Capacity is small |
| Indexed by value | V + 1 | O(nV) | Total value is small |
Since V ≤ n · vmax, the value-indexed version runs in O(n² · vmax). It is still pseudo-polynomial, but now in the magnitude of the values instead of the weights. Neither version helps when both the weights and the values are large.
Common mistakes
- Wrong initial value. If you fill the array with 0 instead of infinity, every value looks reachable at zero weight.
- Taking
dp[total]as the answer. The result is the largest reachable value that fits, not the last cell. - Running the loop forwards. That lets an item be used more than once, which solves the unbounded problem instead.
- Fractional values. The index must be an integer. To use this method, scale the values to integers first, for example by converting dollars to cents.
Exercise
The items have values [3, 4, 5] and weights [109, 2*109, 3109], and the capacity is 310**9. What is the optimal value, and roughly how many table cells does each DP version need?
Show answer
The optimal value is 7: take the first two items, with total weight exactly 3109. The weight-indexed DP needs about 310**9 + 1 cells. The value-indexed DP needs V + 1 = 13 cells.
Exercise
Why must the inner loop in knapsackbyvalue run from total down to v?
Show answer
Going downwards means dp[t - v] still holds its value from before the current item was considered. That way each item adds to a total at most once. Going upwards could add the same item again, which would solve the unbounded problem.