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