Skip to content

1376. Time Needed to Inform All Employees 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
 public:
  int numOfMinutes(int n, int headID, vector<int>& manager,
                   vector<int>& informTime) {
    int ans = 0;

    for (int i = 0; i < n; ++i)
      ans = max(ans, dfs(i, headID, manager, informTime, {}));

    return ans;
  }

 private:
  int dfs(int i, int headID, const vector<int>& manager,
          const vector<int>& informTime, unordered_map<int, int>&& mem) {
    if (const auto it = mem.find(i); it != mem.cend())
      return it->second;
    if (i == headID)
      return 0;

    const int parent = manager[i];
    return mem[i] = informTime[parent] +
                    dfs(parent, headID, manager, informTime, std::move(mem));
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public int numOfMinutes(int n, int headID, int[] manager, int[] informTime) {
    int ans = 0;
    Map<Integer, Integer> mem = new HashMap<>();

    for (int i = 0; i < n; ++i)
      ans = Math.max(ans, dfs(i, headID, manager, informTime, mem));

    return ans;
  }

  int dfs(int i, int headID, int[] manager, int[] informTime, Map<Integer, Integer> mem) {
    if (mem.containsKey(i))
      return mem.get(i);
    if (i == headID)
      return 0;

    final int parent = manager[i];
    mem.put(i, informTime[parent] + dfs(parent, headID, manager, informTime, mem));
    return mem.get(i);
  }
}