Time Needed to Inform All Employees

medium tree dfs bfs

Problem

n employees with headID as the head. manager[i] is the direct manager of i (-1 for head). informTime[i] is how long employee i needs to inform their direct subordinates. Return the time until everyone is informed.

Inputn=7, headID=6, manager=[1,2,3,4,5,6,-1], informTime=[0,6,5,4,3,2,1]
Output21
Path 6→5→4→3→2→1→0 takes 1+2+3+4+5+6 = 21.

def num_of_minutes(n, headID, manager, informTime):
    children = [[] for _ in range(n)]
    for i, m in enumerate(manager):
        if m != -1: children[m].append(i)
    def dfs(u):
        if not children[u]: return 0
        return informTime[u] + max(dfs(c) for c in children[u])
    return dfs(headID)
function numOfMinutes(n, headID, manager, informTime) {
  const children = Array.from({length: n}, () => []);
  for (let i = 0; i < n; i++) if (manager[i] !== -1) children[manager[i]].push(i);
  function dfs(u) {
    if (!children[u].length) return 0;
    let best = 0;
    for (const c of children[u]) best = Math.max(best, dfs(c));
    return informTime[u] + best;
  }
  return dfs(headID);
}
class Solution {
    List> ch;
    int[] inf;
    public int numOfMinutes(int n, int headID, int[] manager, int[] informTime) {
        ch = new ArrayList<>();
        for (int i = 0; i < n; i++) ch.add(new ArrayList<>());
        for (int i = 0; i < n; i++) if (manager[i] != -1) ch.get(manager[i]).add(i);
        inf = informTime;
        return dfs(headID);
    }
    int dfs(int u) {
        if (ch.get(u).isEmpty()) return 0;
        int best = 0;
        for (int c : ch.get(u)) best = Math.max(best, dfs(c));
        return inf[u] + best;
    }
}
int numOfMinutes(int n, int headID, vector& manager, vector& informTime) {
    vector> ch(n);
    for (int i = 0; i < n; i++) if (manager[i] != -1) ch[manager[i]].push_back(i);
    function dfs = [&](int u) -> int {
        if (ch[u].empty()) return 0;
        int best = 0;
        for (int c : ch[u]) best = max(best, dfs(c));
        return informTime[u] + best;
    };
    return dfs(headID);
}
Time: O(n) Space: O(n)