Ad platform~30 min2s · 256 MBtarget O(n × budget × n) time, O(n × budget) spacebacktracking
An ad platform builds bundles of ad slots. A search chooses slots in increasing order of price, and it stops a branch as soon as the next price is too large. It also skips a slot whose price equals the one tried right before it at the same step.
Before the search goes live, the team wants to know how many calls it will make. Running it is not possible, because the count reaches 10^15.
Your team lead says: Tell me the number of calls without running the search.
Write pruned_calls(prices, budget).
budget.start upwards. It stops the loop at the first price larger than the remainder. It skips a position whose price equals the price before it, unless the position is start.i it makes one call with start i + 1 and the remainder reduced by the price.Input: prices = [1, 2, 3, 4, 5], budget = 6
Output: 13The prices are 1, 2, 3, 4, 5 and the budget is 6. Each row is one call of the search, with the number of calls made in its subtree.
| Call | Start | Left to pay | Calls in its subtree |
|---|---|---|---|
| 1 | 0 | 6 | 13 |
| 2 | 1 | 5 | 6 |
| 3 | 2 | 3 | 2 |
| 4 | 3 | 0 | 1 |
| 5 | 3 | 2 | 1 |
| 6 | 4 | 1 | 1 |
| 7 | 5 | 0 | 1 |
| 8 | 2 | 4 | 3 |
| 9 | 3 | 1 | 1 |
| 10 | 4 | 0 | 1 |
| 11 | 3 | 3 | 1 |
| 12 | 4 | 2 | 1 |
| 13 | 5 | 1 | 1 |
The first call has 13 calls in its subtree, so the answer is 13.
Input: prices = [1, 1, 2, 3], budget = 4
Output: 8The prices 1, 1, 2, 3 and a budget of 4 give the search of the lesson. The second 1 is skipped at the top, and the search makes 8 calls.
Input: prices = [5, 7], budget = 3
Output: 1No price is at most 3, so the first call makes no more calls. The answer is 1.
1 ≤ prices.length ≤ 501 ≤ prices[i] ≤ 5001 ≤ budget ≤ 2,000For the prices 1 to 50 and a budget of 1,275, every subset is a path of the search, and the search makes 1,125,899,906,842,624 calls. That is 2^50, below 2^53, so it is exact in every language. The search cannot be run. The same state, a start and a remainder, is reached by many choices, so a table of counts keeps the work small.