691. Spreading the News
A company has n employees numbered 0 to n - 1. The chief is headId, and manager[i] is the direct boss of employee i (the chief has manager[headId] = -1). Everyone else has exactly one boss, so the company forms a tree rooted at the chief.
The chief learns an urgent piece of news at minute 0. When an employee i has the news and has direct reports, it takes informTime[i] minutes before all of those reports have received it at the same moment, and then each of them passes it on in the same way. The value informTime[i] does not matter for employees without reports. Return the number of minutes until the last employee knows. Target O(n) time and avoid recursion, because the chain of command may be very deep.
Example 1
- Input:
- n = 6headId = 2manager = [2,2,-1,1,1,3]informTime = [0,4,3,2,0,0]
- Output:
- 9
- Explanation:
Employee 2 is the chief and informs 0 and 1 at minute 3. Employee 1 informs 3 and 4 four minutes later (minute 7), and employee 3 informs 5 two minutes after that, so everyone knows at minute 9.
Example 2
- Input:
- n = 3headId = 0manager = [-1,0,0]informTime = [5,0,0]
- Output:
- 5
- Explanation:
The chief needs 5 minutes to inform both reports; they have no reports themselves.
Example 3
- Input:
- n = 5headId = 4manager = [4,4,0,0,-1]informTime = [2,0,6,0,3]
- Output:
- 5
- Explanation:
The chief 4 informs employees 0 and 1 at minute 3; employee 0 needs 2 more minutes for employees 2 and 3, giving 5 for the last person. The value for employee 2 is irrelevant because it has no reports.
Constraints
1 ≤ n ≤ 100000
0 ≤ headId < n
manager.length == informTime.length == n
manager[headId] == -1, all other entries are valid employee ids, and the reporting structure is a tree.
0 ≤ informTime[i] ≤ 1000
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 400 msC++ 100 msJava 200 msJavaScript 200 msTypeScript 200 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)