"""0/1 knapsack.

Idea
----
Each item has a weight and a value, and can be taken at most once. Let
``best[c]`` be the highest value achievable with capacity ``c`` using the
items seen so far. For a new item (w, v):

    best[c] = max(best[c], best[c - w] + v)

Iterate ``c`` *downwards* so each item is used at most once; iterating
upwards would let the same item be reused (that is the unbounded knapsack).

Complexity
----------
Time:  O(n * W), where W is the capacity (pseudo-polynomial)
Space: O(W) with the one-dimensional table
"""

from collections.abc import Sequence


def knapsack(weights: Sequence[int], values: Sequence[int], capacity: int) -> int:
    """Return the maximum total value that fits in ``capacity``."""
    if len(weights) != len(values):
        raise ValueError("weights and values must have the same length")
    best = [0] * (capacity + 1)
    for w, v in zip(weights, values):
        for c in range(capacity, w - 1, -1):
            best[c] = max(best[c], best[c - w] + v)
    return best[capacity]
