forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
time-needed-to-inform-all-employees.cpp
60 lines (56 loc) · 1.71 KB
/
time-needed-to-inform-all-employees.cpp
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Time: O(n)
// Space: O(n)
// dfs solution with stack
class Solution {
public:
int numOfMinutes(int n, int headID, vector<int>& manager, vector<int>& informTime) {
unordered_map<int, vector<int>> children;
for (int i = 0; i < manager.size(); ++i) {
if (manager[i] != -1) {
children[manager[i]].emplace_back(i);
}
}
int result = 0;
vector<pair<int, int>> stk = {{headID, 0}};
while (!stk.empty()) {
auto [node, curr] = stk.back(); stk.pop_back();
curr += informTime[node];
result = max(result, curr);
if (!children.count(node)) {
continue;
}
for (const auto& child : children.at(node)) {
stk.emplace_back(child, curr);
}
}
return result;
}
};
// Time: O(n)
// Space: O(n)
// dfs solution with recursion
class Solution2 {
public:
int numOfMinutes(int n, int headID, vector<int>& manager, vector<int>& informTime) {
unordered_map<int, vector<int>> children;
for (int i = 0; i < manager.size(); ++i) {
if (manager[i] != -1) {
children[manager[i]].emplace_back(i);
}
}
return dfs(informTime, children, headID);
}
private:
int dfs(const vector<int>& informTime,
const unordered_map<int, vector<int>>& children,
int node) {
if (!children.count(node)) {
return informTime[node];
}
int result = 0;
for (const auto& child : children.at(node)) {
result = max(result, dfs(informTime, children, child));
}
return result + informTime[node];
}
};