1376 Time Needed to Inform All Employees
https://leetcode.com/problems/time-needed-to-inform-all-employees/submissions/
class Solution {
private class Node {
int time;
List<Node> subs;
public Node(int t) {
time = t;
subs = new ArrayList<>();
}
}
public int numOfMinutes(int n, int headID, int[] manager, int[] informTime) {
Node[] emps = new Node[n];
emps[headID] = new Node(informTime[headID]);
buildGraph(emps, manager, informTime);
dfs(emps[headID]);
return dfs(emps[headID]);
}
private int dfs(Node man) {
if (man == null) return 0;
int tmp = 0;
for (Node sub : man.subs) {
tmp = Math.max(tmp, dfs(sub));
}
return tmp + man.time;
}
private void buildGraph(Node[] emps, int[] manager, int[] informTime) {
for (int i = 0; i < manager.length; i++) {
if (manager[i] == -1) continue;
Node emp = emps[i];
if (emp == null) emp = new Node(informTime[i]);
emps[i] = emp;
Node man = emps[manager[i]];
if (man == null) man = new Node(informTime[manager[i]]);
emps[manager[i]] = man;
man.subs.add(emp);
}
}
}Last updated