Problem
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.
Example 1:
Input: n = 1, headID = 0, manager = [-1], informTime = [0] Output: 0 Explanation: The head of the company is the only employee in the company.
Example 2:
Input: n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0] Output: 1 Explanation: The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all. The tree structure of the employees in the company is shown.
Constraints:
1 <= n <= 105
0 <= headID < n
manager.length == n
0 <= manager[i] < n
manager[headID] == -1
informTime.length == n
0 <= informTime[i] <= 1000
informTime[i] == 0
if employeei
has no subordinates.- It is guaranteed that all the employees can be informed.
Solution
一開始看完題目後,大概可以感覺出來應該用 DFS 來解。用 DFS 計算每一條從 headID
到 leaf 的通知時間總和,最後取最大的時間。
不過由於它傳進來的 manager
是每個 node 的 parent,這樣的資料不利於 DFS。一個方法是,利用 manager
來建立一個 tree,再用 DFS 由上至下地找出所有的 paths。
另外一種方法是,對每一個 node,用 DFS 計算從該點到 headID
的通知時間總和,最後取最大的時間。這和上述的想法差不多,但是方向是由下至上。此外,還需要一個 Map
來記錄每個 node 至 headID
的通知時間總和,這樣可以去除重複計算。例如,先算從 4 到 2 的時間總和,它同時也計算了 0 至 2 的時間總和。之後,當要計算 0 至 2 時,就可以從 Map
中直接取得值。
DFS
- Time:
- Space:
class Solution { public int numOfMinutes(int n, int headID, int[] manager, int[] informTime) { Map<Integer, Integer> memo = new HashMap<>(); int ans = 0; for (int i = 0; i < n; i++) { ans = Math.max(ans, dfs(i, headID, manager, informTime, memo)); } return ans; } private int dfs(int i, int headID, int[] manager, int[] informTime, Map<Integer, Integer> memo) { if (memo.containsKey(i)) { return memo.get(i); } if (i == headID) { return 0; } int parent = manager[i]; int time = informTime[parent] + dfs(parent, headID, manager, informTime, memo); memo.put(i, time); return time; } }
參考
- 1376. Time Needed to Inform All Employees, LeetCode.
- 1376. Time Needed to Inform All Employees, LeetCode Solutions.