Equal Split
Dynamic Programming: lesson 13 of 20
Can any subset hit exactly half the total? Track reachable sums.
Lesson 13 of 20 · 6 min
Equal Split
Step 1 of 7
Total 12, so the target is 6. Only sum zero is reachable before any number is used — the empty subset.
The Idea
Splitting a set into two equal halves sounds like a search over subsets. It is really 0/1 knapsack with the values thrown away: mark sum zero as reachable, then let each number extend every sum already marked. If half the total lights up, the split exists. Backwards iteration keeps each number single-use.
Real-World Example
Two delivery vans and a pallet of crates that must be loaded to the same weight, or the depot scales reject the run. Nobody enumerates loadings. The loader tracks which total weights are still achievable and checks whether half the pallet is one of them.
The Code
nums = [3, 3, 4, 2]
total = sum(nums)
half = total // 2
can = [False] * (half + 1)
can[0] = True # the empty subset reaches zero
for n in nums:
for s in range(half, n - 1, -1): # backwards: each number used once
can[s] = can[s] or can[s - n]
print(can) # [True, False, True, True, True, True, True]
print(total % 2 == 0 and can[half]) # True — 3 + 3 against 4 + 2Your turn
What does this print?
can = [False] * 5
can[0] = True
for n in [1, 3]:
for s in range(4, n - 1, -1):
can[s] = can[s] or can[s - n]
print(can)Mini quiz
1 / 3