- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 47 lines of Python from the credited upstream file 3373.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def maxTargetNodes(3 self,4 edges1: list[list[int]],5 edges2: list[list[int]]6 ) -> list[int]:7 n = len(edges1) + 18 m = len(edges2) + 19 graph1 = self._buildGraph(edges1)10 graph2 = self._buildGraph(edges2)11 parity1 = [False] * n12 parity2 = [False] * m 13 even1 = self._dfs(graph1, 0, -1, parity1, True)14 even2 = self._dfs(graph2, 0, -1, parity2, True)15 odd1 = n - even116 odd2 = m - even217 18 19 20 return [(even1 if parity1[i] else odd1) + max(even2, odd2)21 for i in range(n)]22 23 def _dfs(24 self,25 graph: list[list[int]],26 u: int,27 prev: int,28 parity: list[bool],29 isEven: bool30 ) -> int:31 """32 Returns the number of nodes that can be reached from u with even steps.33 """34 res = 1 if isEven else 035 parity[u] = isEven36 for v in graph[u]:37 if v != prev:38 res += self._dfs(graph, v, u, parity, not isEven)39 return res40 41 def _buildGraph(self, edges: list[list[int]]) -> list[list[int]]:42 graph = [[] for _ in range(len(edges) + 1)]43 for u, v in edges:44 graph[u].append(v)45 graph[v].append(u)46 return graph47