forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
time-needed-to-inform-all-employees.py
57 lines (50 loc) · 1.56 KB
/
time-needed-to-inform-all-employees.py
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
# Time: O(n)
# Space: O(n)
import collections
# dfs solution with stack
class Solution(object):
def numOfMinutes(self, n, headID, manager, informTime):
"""
:type n: int
:type headID: int
:type manager: List[int]
:type informTime: List[int]
:rtype: int
"""
children = collections.defaultdict(list)
for child, parent in enumerate(manager):
if parent != -1:
children[parent].append(child)
result = 0
stk = [(headID, 0)]
while stk:
node, curr = stk.pop()
curr += informTime[node]
result = max(result, curr)
if node not in children:
continue
for c in children[node]:
stk.append((c, curr))
return result
# Time: O(n)
# Space: O(n)
# dfs solution with recursion
class Solution2(object):
def numOfMinutes(self, n, headID, manager, informTime):
"""
:type n: int
:type headID: int
:type manager: List[int]
:type informTime: List[int]
:rtype: int
"""
def dfs(informTime, children, node):
return (max(dfs(informTime, children, c)
for c in children[node])
if node in children
else 0) + informTime[node]
children = collections.defaultdict(list)
for child, parent in enumerate(manager):
if parent != -1:
children[parent].append(child)
return dfs(informTime, children, headID)