Payments app~20 min2s · 256 MBtarget O(n) time, O(n) spacetree-recursion
You work on a payments app. Its teams form a reporting chart: every team has one boss team, except the top team. Each team spends some processing fees of its own. The finance dashboard shows, for every team, the total fees of that team and of all the teams below it.
Your team lead asks: "Give me the rolled-up total for every team." The chart can hold 100,000 teams, and the numbers of a team and of its boss are not in any particular order.
Write rolled_up_totals(parents, spend).
0 to n - 1.parents[i] is the boss of team i, or -1 for the top team. Exactly one team has -1, and the teams form one chart with no loops.spend[i] is the fees of team i alone.n numbers. Entry i is the total fees of team i and every team below it, at any depth.Input: parents = [-1, 0, 0, 1, 1, 2], spend = [5, 10, 20, 1, 2, 3]
Output: [41, 13, 23, 1, 2, 3]| Team | Own fees | Teams below it | Rolled-up total |
|---|---|---|---|
| 3 | 1 | none | 1 |
| 4 | 2 | none | 2 |
| 5 | 3 | none | 3 |
| 1 | 10 | teams 3 and 4 | 10 + 1 + 2 = 13 |
| 2 | 20 | team 5 | 20 + 3 = 23 |
| 0 | 5 | teams 1 to 5 | 5 + 13 + 23 = 41 |
Input: parents = [2, -1, 1, 2], spend = [4, 3, 2, 1]
Output: [4, 10, 7, 1]The top team is team 1. Team 2 reports to it, and teams 0 and 3 report to team 2. A boss does not always have a smaller number than its teams.
Input: parents = [-1], spend = [9]
Output: [9]1 ≤ len(parents) ≤ 100,000, and spend has the same length.-1 ≤ parents[i] ≤ n - 1, with exactly one -1.0 ≤ spend[i] ≤ 1,000,000,000For every team, checking every other team by climbing up its chain of bosses takes more than 10^14 steps when the chart is a chain of 100,000 teams. Each team's total is its own fees plus the totals of the teams directly below it. If the teams are handled in an order where lower teams come first, every team needs one addition. That is 100,000 additions.