Chat app~30 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-124tree-recursion
A chat app shows its company directory as an org chart. Each person has at most two direct reports. A survey gave every person a mood score. Scores can be negative.
Your team lead wants the happiest chain of people: a group of people who are linked one after another by reporting lines, with the largest total score. The chain can start and end anywhere in the chart and does not need to include the head of the company. It has at least one person.
Write best_chain_mood(values, left, right).
0 to n - 1, and person 0 is the head. There is at least one person.values[i] is the mood score of person i. left[i] and right[i] are the numbers of the direct reports of person i, or -1 where there is none.Input: values = [-10, 9, 20, 15, 7], left = [1, -1, 3, -1, -1], right = [2, -1, 4, -1, -1]
Output: 42Person 0 (score -10) has the reports 1 (score 9) and 2 (score 20). Person 2 has the reports 3 (score 15) and 4 (score 7).
Work from the bottom up. Each person has two numbers. The best chain that turns at this person is their score plus the better side from each report, ignoring a side that is negative. The best chain that goes up from this person is their score plus only the better single side.
| Person | Left side | Right side | Best turning here | Best so far | Goes up |
|---|---|---|---|---|---|
4 |
0 | 0 | 7 | 7 | 7 |
3 |
0 | 0 | 15 | 15 | 15 |
2 |
15 | 7 | 42 | 42 | 35 |
1 |
0 | 0 | 9 | 42 | 9 |
0 |
9 | 35 | 34 | 42 | 25 |
The best chain is 15, 20, 7. It does not include the head.
Input: values = [-3, -1], left = [1, -1], right = [-1, -1]
Output: -1Every score is negative, so the best chain is the single person with -1. A chain needs at least one person.
Input: values = [5], left = [-1], right = [-1]
Output: 51 ≤ length of values = length of left = length of right ≤ 10^5-1000 ≤ values[i] ≤ 1000left and right is -1 or a person number from 1 to n - 10Trying every pair of ends costs billions of steps on a chart of 100,000 people. A chain-shaped chart also makes nested calls 100,000 deep, more than Python allows by default. The best total is at most 10^8, which fits in a 32-bit integer.
Handle each person once, from the bottom up, with a loop and a list.