- 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
- 36 lines of Python from the credited upstream file 3372.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 k: int7 ) -> list[int]:8 graph1 = self._buildGraph(edges1)9 graph2 = self._buildGraph(edges2)10 maxReachableInGraph2 = 011 12 if k > 0:13 for i in range(len(edges2) + 1):14 maxReachableInGraph2 = max(maxReachableInGraph2,15 self._dfs(graph2, i, -1, k - 1))16 17 return [maxReachableInGraph2 + self._dfs(graph1, i, -1, k)18 for i in range(len(edges1) + 1)]19 20 def _dfs(self, graph: list[list[int]], u: int, prev: int, k: int) -> int:21 """Returns the number of nodes that can be reached from u with k steps."""22 if k == 0:23 return 124 res = 025 for v in graph[u]:26 if v != prev:27 res += self._dfs(graph, v, u, k - 1)28 return 1 + res29 30 def _buildGraph(self, edges: list[list[int]]) -> list[list[int]]:31 graph = [[] for _ in range(len(edges) + 1)]32 for u, v in edges:33 graph[u].append(v)34 graph[v].append(u)35 return graph36