"""Subset sum (and partition into two equal halves).

Idea
----
Can some subset of non-negative integers add up to ``target``? Keep the set
of reachable sums as a boolean table: ``reachable[s]`` is True if some subset
of the numbers seen so far sums to ``s``. For each new number x, every
reachable s also makes s + x reachable. Iterate s downwards so each number is
used at most once (the same trick as 0/1 knapsack).

A compact Python alternative stores reachable sums as the bits of one big
integer: ``bits |= bits << x``.

Complexity
----------
Time:  O(n * target) (pseudo-polynomial; the general problem is NP-complete)
Space: O(target)
"""

from collections.abc import Sequence


def subset_sum(numbers: Sequence[int], target: int) -> bool:
    if target < 0 or any(x < 0 for x in numbers):
        raise ValueError("numbers and target must be non-negative")
    reachable = [True] + [False] * target
    for x in numbers:
        for s in range(target, x - 1, -1):
            if reachable[s - x]:
                reachable[s] = True
    return reachable[target]


def subset_sum_bits(numbers: Sequence[int], target: int) -> bool:
    """Same answer using an integer as a bitset (often much faster in Python)."""
    bits = 1  # bit s set <=> sum s reachable
    for x in numbers:
        bits |= bits << x
    return bool(bits >> target & 1)


def can_partition(numbers: Sequence[int]) -> bool:
    """Can the numbers be split into two groups with equal sums?"""
    total = sum(numbers)
    return total % 2 == 0 and subset_sum(numbers, total // 2)
