Leetcode

Time Needed to Inform All Employees

  • Time:O(n)
  • Space:O(n)

C++

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>&& memo) {
    if (memo.count(i))
      return memo[i];
    if (i == headID)
      return 0;

    const int parent = manager[i];
    return memo[i] = informTime[parent] +
                     dfs(parent, headID, manager, informTime, move(memo));
  }
};

JAVA

class Solution {
  public int numOfMinutes(int n, int headID, int[] manager, int[] informTime) {
    int ans = 0;
    Map<Integer, Integer> memo = new HashMap<>();

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

    return ans;
  }

  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;

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