- 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
- 48 lines of Java from the credited upstream file 3203.java.
- The implementation visibly relies on sequence storage.
- 3 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 public int minimumDiameterAfterMerge(int[][] edges1, int[][] edges2) {3 final int diameter1 = getDiameter(edges1);4 final int diameter2 = getDiameter(edges2);5 final int combinedDiameter = (diameter1 + 1) / 2 + (diameter2 + 1) / 2 + 1;6 return Math.max(Math.max(diameter1, diameter2), combinedDiameter);7 }8 9 private int getDiameter(int[][] edges) {10 final int n = edges.length + 1;11 List<Integer>[] graph = new List[n];12 13 for (int i = 0; i < n; i++)14 graph[i] = new ArrayList<>();15 16 for (int[] edge : edges) {17 final int u = edge[0];18 final int v = edge[1];19 graph[u].add(v);20 graph[v].add(u);21 }22 23 int[] maxDiameter = new int[1];24 maxDepth(graph, 0, -1, maxDiameter);25 return maxDiameter[0];26 }27 28 29 30 private int maxDepth(List<Integer>[] graph, int u, int prev, int[] maxDiameter) {31 int maxSubDepth1 = 0;32 int maxSubDepth2 = 0;33 for (final int v : graph[u]) {34 if (v == prev)35 continue;36 final int maxSubDepth = maxDepth(graph, v, u, maxDiameter);37 if (maxSubDepth > maxSubDepth1) {38 maxSubDepth2 = maxSubDepth1;39 maxSubDepth1 = maxSubDepth;40 } else if (maxSubDepth > maxSubDepth2) {41 maxSubDepth2 = maxSubDepth;42 }43 }44 maxDiameter[0] = Math.max(maxDiameter[0], maxSubDepth1 + maxSubDepth2);45 return 1 + maxSubDepth1;46 }47}48