-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy path1376-time-needed-to-inform-all-employees.js
50 lines (44 loc) · 1.7 KB
/
1376-time-needed-to-inform-all-employees.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* 1376. Time Needed to Inform All Employees
* https://leetcode.com/problems/time-needed-to-inform-all-employees/
* Difficulty: Medium
*
* A company has n employees with a unique ID for each employee from 0 to n - 1. The head
* of the company is the one with headID.
*
* Each employee has one direct manager given in the manager array where manager[i] is the
* direct manager of the i-th employee, manager[headID] = -1. Also, it is guaranteed that
* the subordination relationships have a tree structure.
*
* The head of the company wants to inform all the company employees of an urgent piece of
* news. He will inform his direct subordinates, and they will inform their subordinates,
* and so on until all employees know about the urgent news.
*
* The i-th employee needs informTime[i] minutes to inform all of his direct subordinates
* (i.e., After informTime[i] minutes, all his direct subordinates can start spreading the news).
*
* Return the number of minutes needed to inform all the employees about the urgent news.
*/
/**
* @param {number} n
* @param {number} headID
* @param {number[]} manager
* @param {number[]} informTime
* @return {number}
*/
var numOfMinutes = function(n, headID, manager, informTime) {
const adjacencyList = Array.from({ length: n }, () => []);
for (let i = 0; i < n; i++) {
if (manager[i] !== -1) {
adjacencyList[manager[i]].push(i);
}
}
return calculateTime(headID);
function calculateTime(employee) {
let maxSubordinateTime = 0;
for (const subordinate of adjacencyList[employee]) {
maxSubordinateTime = Math.max(maxSubordinateTime, calculateTime(subordinate));
}
return informTime[employee] + maxSubordinateTime;
}
};