Dynamic programming · 3 / 15 Theory

The knapsack and subset sum

In the 0/1 knapsack each item is either taken whole or not taken. The state is the capacity that is left; for each item you decide whether it is worth using.

def knapsack(items, capacity):
    """items: list of (weight, value). Largest value without exceeding capacity."""
    dp = [0] * (capacity + 1)               # dp[w]: best value with capacity w
    for weight, value in items:
        for w in range(capacity, weight - 1, -1):    # backwards! each item only once
            dp[w] = max(dp[w], dp[w - weight] + value)
    return dp[capacity]

print(knapsack([(10, 60), (20, 100), (30, 120)], 50))    # 220

def can_form(numbers, target):
    reachable = {0}                        # sums that can be formed
    for x in numbers:
        reachable |= {s + x for s in reachable}
    return target in reachable

print(can_form([3, 34, 4, 12, 5, 2], 9))         # True   (4 + 5)
print(can_form([3, 34, 4, 12, 5, 2], 30))        # False

The capacity loop goes from high to low so that the same item is not used twice (if it went from low to high, you would get the knapsack with unlimited items). The subset sum (does any group add up exactly to target?) is a knapsack where only whether a sum is reachable matters.

  • Cost: O(n · capacity), which is far less than trying all 2ⁿ subsets.
  • With huge weights the table is infeasible: DP is pseudo-polynomial (it depends on the numeric value of the capacity).
  • Splitting into two equal groups means looking for a subset with sum total / 2.

You practice it in The 0/1 knapsack and Split into two equal halves.