Ad platform~25 min2s · 256 MBtarget O(2^(n/2)) time, O(2^(n/2)) spacedivide-and-conquer
An ad app sells slots on a page. Each slot has a price in units. An advertiser has a budget and wants to know how many bundles of slots cost exactly that budget.
A bundle is any set of slots, and it may be empty, which costs 0. Two slots with the same price are different slots.
Your team lead says: There can be 34 slots. Do not try every bundle. Split the slots in two halves.
Write count_bundles(prices, budget).
budget.Input: prices = [3, 5, 2, 6], budget = 8
Output: 2Split the four prices into [3, 5] and [2, 6]. List every total of each half, and look for pairs that add up to 8.
| Step | Left half [3, 5] |
Right half [2, 6] |
|---|---|---|
| Every total of a set | [0, 3, 5, 8] | [0, 2, 6, 8] |
| Needs from the other half for budget 8 | [8, 5, 3, 0] | [8, 6, 2, 0] |
The pair of totals 0 and 8 is the bundle [2, 6], and the pair 8 and 0 is the bundle [3, 5]. There are 2 bundles.
Input: prices = [4, 7], budget = 0
Output: 1The empty bundle costs 0, so the count is 1.
Input: prices = [1, 1, 1, 1], budget = 2
Output: 6Four slots with the price 1 make 6 bundles of two slots.
1 ≤ prices.length ≤ 341 ≤ prices[i] ≤ 1,000,0000 ≤ budget ≤ 34,000,000With 34 slots there are 17,179,869,184 bundles. Even at a billion bundles a second that is about 17 seconds, and Python is far slower. Two halves of 17 slots have 131,072 bundles each, and matching them takes about 262,144 steps.