Meet in the Middle
In short: when a search space is every subset of n items, trying all 2ⁿ is hopeless past about n = 40 — but every subset is exactly one subset of the left half paired with one subset of the right half. Enumerate each half's subset sums on its own (2^(n/2) of them), sort one half, and for each sum in the other half, one binary search finds its best partner. That turns a trillion into about a million: the square root of the search space, traded for memory instead of time.

When Quarry restarts, it warms its cache by preloading index segments from disk, so the first queries don't all miss. The cache has a fixed budget in bytes, and each segment has a size. The warmer wants the set of segments that fills the budget as fully as possible without going over. A fuller cache means fewer cold reads.
That's fine for four segments. A real index has about forty, and 2⁴⁰ is roughly a trillion subsets. The knapsack table from the dynamic programming lessons doesn't rescue you either, because it needs one column per byte of budget, and a cache budget is tens of billions of bytes. Backtracking with pruning helps on friendly inputs, but its worst case is still all 2⁴⁰ subsets.
Meet in the middle gets you to about 2²⁰ work, a million instead of a trillion, with an idea that sounds too simple to work.
Split, enumerate, join
Cut the segments into two halves. Every subset of all the segments is exactly one subset of the left half together with one subset of the right half, and its total is the left total plus the right total. So:
- Enumerate every subset sum of the left half, and sort them.
- Enumerate every subset sum of the right half.
- Join: for each right sum
r, the best partner is the largest left sum that is at mostbudget - r. In a sorted list, that's one binary search.
With 40 segments, each half has 2²⁰ ≈ one million sums. Sorting one half and running a million binary searches costs about 2²⁰ × 20 steps, around twenty million, where brute force needed a trillion.
Enumerating a half is easiest by doubling: start from [0], and for each
item, keep every sum you have and add a copy with the item included.
Here is the same enumeration as a decision tree. Each level decides one item: the left branch skips it and the right branch takes it. The leaves are the half's subset sums, and there are exactly 2³ = 8 of them.
One half of the search. Each level doubles the sums, so a half of n/2 items has 2^(n/2) leaves. Both halves together hold far fewer sums than the full tree.
Nothing chosen yet, so the sum is 0. Binary tree, 15 nodes, height 4. At node 0.
The full tree over six items would have 64 leaves. The two half-trees have 8 each.
def subset_sums(items):
sums = [0]
for x in items:
sums = sums + [s + x for s in sums]
return sums
sizes = [7, 13, 22, 31, 18, 9]
left = subset_sums(sizes[:3])
right = subset_sums(sizes[3:])
print(len(left), len(right), len(left) * len(right))