Approach
Depth-first search
For Finish Time of Tasks I, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 60 lines of Python from the credited upstream file finish-time-of-tasks-i.py.
- The implementation visibly relies on sequence storage, cached states.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution(object):6 def finishTime(self, n, edges, baseTime):7 """8 :type n: int9 :type edges: List[List[int]]10 :type baseTime: List[int]11 :rtype: int12 """13 POS_INF, NEG_INF = float("inf"), float("-inf")14 def iter_dfs():15 dp = [0]*n16 stk = [(1, 0)]17 while stk:18 step, u = stk.pop()19 if step == 1:20 stk.append((2, u))21 for v in reversed(adj[u]):22 stk.append((1, v))23 elif step == 2:24 mx, mn = NEG_INF, POS_INF25 for v in adj[u]:26 mx, mn = max(mx, dp[v]), min(mn, dp[v])27 dp[u] = ((2*mx-mn) if mx is not NEG_INF else 0)+baseTime[u]28 return dp[0]29 30 adj = [[] for _ in xrange(n)]31 for u, v in edges:32 adj[u].append(v)33 return iter_dfs()34 35 36373839class Solution2(object):40 def finishTime(self, n, edges, baseTime):41 """42 :type n: int43 :type edges: List[List[int]]44 :type baseTime: List[int]45 :rtype: int46 """47 POS_INF, NEG_INF = float("inf"), float("-inf")48 def dfs(u):49 mx, mn = NEG_INF, POS_INF50 for v in adj[u]:51 ret = dfs(v)52 mx, mn = max(mx, ret), min(mn, ret)53 return ((2*mx-mn) if mx is not NEG_INF else 0)+baseTime[u]54 55 adj = [[] for _ in xrange(n)]56 for u, v in edges:57 adj[u].append(v)58 return dfs(0)59 60