Ad platform~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-437tree-recursion · prefix-sum-hashmap
An ad platform stores a campaign as a tree. The top is the campaign, each ad group inside it can hold at most two smaller groups, and so on. Every group has a budget change for today: a positive number adds money and a negative one removes it.
Your team lead wants to know how many chains of groups have a total change of exactly k. A chain starts at any group and goes down through the groups inside it, one at a time. It can stop at any group.
Write count_budget_chains(values, left, right, k).
0 to n - 1, and group 0 is the campaign. An empty campaign has three empty lists.values[i] is the change of group i. left[i] and right[i] are the numbers of the groups inside it, or -1 where there is none.k. Chains that cover different groups count separately, even if their totals are equal.Input: values = [5, 3, -2, 2, 1], left = [1, 3, -1, -1, -1], right = [2, 4, -1, -1, -1], k = 3
Output: 2Group 0 (change 5) holds 1 (change 3) and 2 (change -2). Group 1 holds 3 (change 2) and 4 (change 1). The two chains are [3] (group 1 alone) and 5, -2 (groups 0 and 2).
Keep the running total from the campaign down to each group. A chain that ends here and has the total k starts right below an earlier group whose running total is this total minus k. The empty start has the running total 0.
| Arrive at | Running total | Earlier totals on the way down | Look for | Chains found |
|---|---|---|---|---|
0 |
5 | 0 | 2 | 0 |
1 |
8 | 0, 5 | 5 | 1 (the chain [3]) |
3 |
10 | 0, 5, 8 | 7 | 0 |
4 |
9 | 0, 5, 8 | 6 | 0 |
2 |
3 | 0, 5 | 0 | 1 (the chain 5, -2) |
The total is 2. The totals of group 1's side are dropped when the walk leaves it, so group 2 does not see them.
Input: values = [0, 0, 0], left = [1, 2, -1], right = [-1, -1, -1], k = 0
Output: 6A chain of three groups, each with change 0. Three chains of one group, two of two groups and one of three: 6 in all.
Input: values = [], left = [], right = [], k = 5
Output: 00 ≤ length of values = length of left = length of right ≤ 10^5-1000 ≤ values[i] ≤ 1000left and right is -1 or a group number from 1 to n - 10-10^9 ≤ k ≤ 10^9A campaign can be a chain of 100,000 groups. Starting a downward walk at every group costs about n^2 / 2 steps on it. The answer can also be as large as about 5 x 10^9, which does not fit in a 32-bit integer. Use a 64-bit number to count.
Keep one running total from the top, and a count of how many times each running total has been seen on the way down.