Monitoring~18 min2s · 256 MBtarget O(n + q) time, O(n) spaceclassic twin: lc-509recursion
A monitoring system escalates an alert in steps. The weight of step n is the weight of step n - 1 plus the weight of step n - 2, with weight 0 for step 0 and 1 for step 1. A first version computes it with a function that calls itself twice.
fib(n): if n < 2, return n. Otherwise return fib(n - 1) + fib(n - 2).The team wants to know what this function costs before it goes into the alert path.
Write fib_cost(ns).
n in ns, consider the call fib(n) above, with fib(0) = 0 and fib(1) = 1.fib(n), the number of calls made (the first call and every leaf call included), and the deepest stack, counting the first call.n, in order, it holds the three numbers value, calls, deepest.fib for large n. The call counts reach 6 × 10^14.Input: ns = [4]
Output: [3, 9, 4]Take fib(4). The recursion tree has one node for each call.
| Level | Calls on this level |
|---|---|
| 1 | fib(4) |
| 2 | fib(3), fib(2) |
| 3 | fib(2), fib(1), fib(1), fib(0) |
| 4 | fib(1), fib(0) |
There are 9 calls, and the value is 3. The longest path is fib(4), fib(3), fib(2), fib(1): four frames.
The call fib(2) appears twice, so its work is done twice. The answer is [3, 9, 4].
Input: ns = [0, 1]
Output: [0, 1, 1, 1, 1, 1]The calls fib(0) and fib(1) are leaves. Each makes one call, has depth 1, and returns its own value. The answer is [0, 1, 1, 1, 1, 1].
Input: ns = [10, 20]
Output: [55, 177, 10, 6765, 21891, 20]The call fib(10) makes 177 calls, and fib(20) makes 21,891. The values are 55 and 6,765. The depth is n.
1 ≤ ns.length ≤ 5,0000 ≤ ns[i] ≤ 70The value fib(70) is 190,392,490,709,135, and the calls are 616,123,042,340,257. Neither can be reached by running the function. The call count follows its own rule, calls(n) = 1 + calls(n - 1) + calls(n - 2), which a table of 71 numbers computes at once.