~/problems / Backtracking

Split apples into two fair groups

easy ~15 min

You have a pile of apples with known weights and want to split them into two groups (either may be empty) so the group totals are as close as possible. Write min_difference(weights) that returns the smallest possible |total_A - total_B|.

  • 1 <= len(weights) <= 20; each weight is in [1, 10^9].
  • With at most 20 apples there are at most 2^20 ≈ 1 million ways to assign them, so trying every assignment works. Write it as recursion: for apple i, put it in group A or group B, and at the end compare totals. (A bitmask loop is also fine.)
min_difference([8, 1, 4, 6, 3])   # 0   ({8, 3} and {1, 4, 6} both weigh 11)
min_difference([10])              # 10
min_difference([5, 9])            # 4

Topic: Recursion and backtracking. Choose, recurse, un-choose: subsets, permutations, N-queens, pruning.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc