Ad platform~20 min2s · 256 MBtarget O(top + q) time, O(top) spacerecursion
An ad platform splits a campaign budget with a recursive rule. A call on n hours is a leaf when n <= 1. Otherwise it scans its n hours, then calls itself on n - 1 hours and on n // 2 hours.
Before a release, an engineer wants three numbers for each n. They are the calls the rule makes, the frames open at the deepest point, and the total work.
Write budget_cost(ns).
n <= 1) does 1 unit of work and makes no calls. Any other call does n units of work, then makes the call on n - 1 followed by the call on n // 2.n in ns, find the number of calls, with the first call and every leaf included.n, in order, it holds calls, frames, work.n: the calls reach 264,830,889,563.Input: ns = [5]
Output: [13, 5, 25]Take n = 5. The tree has one node for each call. Level 2 holds the calls on 4 and on 2.
| Level | Calls on this level | Work of the level |
|---|---|---|
| 1 | 5 | 5 |
| 2 | 4, 2 | 4 + 2 = 6 |
| 3 | 3, 2, 1, 1 | 3 + 2 + 1 + 1 = 7 |
| 4 | 2, 1, 1, 1 | 2 + 1 + 1 + 1 = 5 |
| 5 | 1, 1 | 2 |
There are 13 calls and the total work is 25. The longest path is 5, 4, 3, 2, 1: five frames. The answer is [13, 5, 25].
Input: ns = [0, 1]
Output: [1, 1, 1, 1, 1, 1]Both 0 and 1 are leaves. Each makes 1 call, holds 1 frame and does 1 unit of work.
Input: ns = [10, 20]
Output: [59, 10, 138, 389, 20, 1004]The call on 10 makes 59 calls with 138 units of work. The call on 20 makes 389 calls with 1,004 units. The stack is 10 and 20 frames deep.
1 ≤ ns.length ≤ 1,0000 ≤ ns[i] ≤ 1,000At n = 1,000 the rule makes 264,830,889,563 calls, so it cannot be run. But the stack follows one branch and is at most 1,000 frames deep. Each count follows the same rule as the function, so a table of 1,001 entries holds them all.