Dynamic programmingAnimated
Subset Sum
Can some subset add up to the target?
Time
O(n · target)
Extra space
O(target)
Use it for
Budgeting, partitioning.
How it works
- Can some subset of the numbers add up to the target?
- Keep a row reach[s] = "is sum s possible?". Only reach[0] (empty subset) starts true.
- For each number x, any sum s that was reachable makes s + x reachable too. Update from high to low so x is used at most once.
- The answer is reach[target]. O(n × target).
Watch it run
Loading animation…