Approach
Depth-first search
For Maximize the Number of Target Nodes After Connecting Trees II, 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
- 49 lines of Java from the credited upstream file 3373.java.
- The implementation visibly relies on sequence storage.
- 4 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.
1class Solution {2 public int[] maxTargetNodes(int[][] edges1, int[][] edges2) {3 final int n = edges1.length + 1;4 final int m = edges2.length + 1;5 List<Integer>[] graph1 = buildGraph(edges1, n);6 List<Integer>[] graph2 = buildGraph(edges2, m);7 boolean[] parity1 = new boolean[n];8 boolean[] parity2 = new boolean[m]; 9 final int even1 = dfs(graph1, 0, -1, parity1, true);10 final int even2 = dfs(graph2, 0, -1, parity2, true);11 final int odd1 = n - even1;12 final int odd2 = m - even2;13 int[] ans = new int[n];14 15 for (int i = 0; i < n; i++) {16 final int tree1 = parity1[i] ? even1 : odd1;17 18 19 final int tree2 = Math.max(even2, odd2);20 ans[i] = tree1 + tree2;21 }22 23 return ans;24 }25 26 27 private int dfs(List<Integer>[] graph, int u, int prev, boolean[] parity, boolean isEven) {28 int res = isEven ? 1 : 0;29 parity[u] = isEven;30 for (final int v : graph[u])31 if (v != prev)32 res += dfs(graph, v, u, parity, !isEven);33 return res;34 }35 36 private List<Integer>[] buildGraph(int[][] edges, int n) {37 List<Integer>[] graph = new ArrayList[n];38 for (int i = 0; i < n; i++)39 graph[i] = new ArrayList<>();40 for (int[] edge : edges) {41 final int u = edge[0];42 final int v = edge[1];43 graph[u].add(v);44 graph[v].add(u);45 }46 return graph;47 }48}49