AlgoMaster Logo

Time Needed to Inform All Employees

n=6,headID=2,manager=[2, 2, -1, 2, 2, 2],informTime=[0, 0, 1, 0, 0, 0]
1class Solution {
2    public int numOfMinutes(int n, int headID, int[] manager, int[] informTime) {
3        List<List<Integer>> subordinates = new ArrayList<>();
4        for (int i = 0; i < n; i++) {
5            subordinates.add(new ArrayList<>());
6        }
7        for (int i = 0; i < n; i++) {
8            if (manager[i] != -1) {
9                subordinates.get(manager[i]).add(i);
10            }
11        }
12
13        int[] memo = new int[n];
14        Arrays.fill(memo, -1);
15
16        return dfs(headID, subordinates, informTime, memo);
17    }
18
19    private int dfs(int currentId, List<List<Integer>> subordinates,
20                    int[] informTime, int[] memo) {
21        if (memo[currentId] != -1) {
22            return memo[currentId];
23        }
24
25        int max = 0;
26        for (int sub : subordinates.get(currentId)) {
27            max = Math.max(max, dfs(sub, subordinates, informTime, memo));
28        }
29
30        memo[currentId] = informTime[currentId] + max;
31        return memo[currentId];
32    }
33}
0 / 35
0inform: 01inform: 02inform: 13inform: 04inform: 05inform: 0Call Stack:(empty)Memo:(empty)Legend:Not visitedVisitingComputedMemoized