Problem solution · Python

Maximize the Number of Target Nodes After Connecting Trees II

Maximize the Number of Target Nodes After Connecting Trees II: a Python solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Direct simulation
Source
walkccc LeetCode Solutions
Length
47 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Direct simulation

For Maximize the Number of Target Nodes After Connecting Trees II, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMaximize the Number of Target Nodes After Connecting Trees II · PythonPython
Use this to learn the idea, then write your own version.
class Solution:  def maxTargetNodes(      self,      edges1: list[list[int]],      edges2: list[list[int]]  ) -> list[int]:    n = len(edges1) + 1    m = len(edges2) + 1    graph1 = self._buildGraph(edges1)    graph2 = self._buildGraph(edges2)    parity1 = [False] * n    parity2 = [False] * m  # placeholder (parity2 is not used)    even1 = self._dfs(graph1, 0, -1, parity1, True)    even2 = self._dfs(graph2, 0, -1, parity2, True)    odd1 = n - even1    odd2 = m - even2     # Can connect the current node in tree1 to either an even node or an odd    # node in tree2.    return [(even1 if parity1[i] else odd1) + max(even2, odd2)            for i in range(n)]   def _dfs(      self,      graph: list[list[int]],      u: int,      prev: int,      parity: list[bool],      isEven: bool  ) -> int:    """    Returns the number of nodes that can be reached from u with even steps.    """    res = 1 if isEven else 0    parity[u] = isEven    for v in graph[u]:      if v != prev:        res += self._dfs(graph, v, u, parity, not isEven)    return res   def _buildGraph(self, edges: list[list[int]]) -> list[list[int]]:    graph = [[] for _ in range(len(edges) + 1)]    for u, v in edges:      graph[u].append(v)      graph[v].append(u)    return graph 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗