Problem: 2063C - Remove Exactly Two
Language: java

Solution 1 (runtime: 859 ms):
import java.util.*;
import java.io.*;
import java.math.*;

public class sub {

	static int mod = 998244353;

	public static void main(String args[]) throws IOException {
		int t = sc.nextInt();
		while(t-->0) {
			int n = sc.nextInt();
			ArrayList<ArrayList<Integer>> adj = new ArrayList();
			for(int i = 0;i<n;i++)adj.add(new ArrayList());
			int deg[] = new int[n];
			for(int i = 0;i<n-1;i++) {
				int u = sc.nextInt()-1;
				int v = sc.nextInt()-1;
				adj.get(u).add(v);
				adj.get(v).add(u);
				deg[u]++;
				deg[v]++;
			}
			TreeMap<Integer, Integer> tm = new TreeMap(Collections.reverseOrder());
			for(int i = 0;i<deg.length;i++) {
				tm.put(deg[i], tm.getOrDefault(deg[i], 0)+1);
			}
			int ans = 0;
			for(int i = 0;i<n;i++) {
				for(int j : adj.get(i)) {
					ans = Math.max(ans, deg[j]+deg[i]-2);
					tm.put(deg[j], tm.get(deg[j])-1);
					if(tm.get(deg[j])==0) {
						tm.remove(deg[j]);
					}
				}
				tm.put(deg[i], tm.get(deg[i])-1);
				if(tm.get(deg[i])==0) {
					tm.remove(deg[i]);
				}
				//out.println(pq);
				ans=Math.max(ans, deg[i]+(tm.isEmpty() ? 0: tm.firstKey())-1);
				for(int j : adj.get(i)) {
					tm.put(deg[j], tm.getOrDefault(deg[j], 0)+1);
				}
				tm.put(deg[i], tm.getOrDefault(deg[i],0)+1);
			}
			out.println(ans);
		}
		out.close();
	}

//	static long bincoef(int n, int k) {
//	    if (n < k) return 0L;
//	    return (p[n] * pow((p[n - k] * p[k]) % mod, mod - 2, mod)) % mod;
//	}
	


	static long pow(long a, long b, long mod) {
		if (b == 0) {
			return 1L;
		}
		long val = pow(a, b / 2, mod);
		if (b % 2 == 0) {
			return val * val % mod;
		}
		return val * val % mod * a % mod;
	}

	static long gcd(long a, long b) {
		if (b == 0) {
			return a;
		}
		return gcd(b, a % b);
	}

	static long lcm(long a, long b) {
		return a * b / gcd(a, b);
	}

	static Kattio sc = new Kattio();
	static PrintWriter out = new PrintWriter(System.out);

	static class Kattio {

		static BufferedReader r;
		static StringTokenizer st;

		public Kattio() {
			r = new BufferedReader(new InputStreamReader(System.in));
		}

		public String next() {
			try {
				while (st == null || !st.hasMoreTokens()) {
					st = new StringTokenizer(r.readLine());
				}
				return st.nextToken();
			} catch (Exception e) {
				return null;
			}
		}

		public int nextInt() {
			return Integer.parseInt(next());
		}

		public long nextLong() {
			return Long.parseLong(next());
		}

		public double nextDouble() {
			return Double.parseDouble(next());
		}
	}
}

Solution 2 (runtime: 905 ms):

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    static int m = 1000000007, M = 998244353;
    static long inf = (long) 1e18;

    static long timer = 0, max = -1;

    public static void main(String[] args) {
        FastReader next = new FastReader();
        int t = next.nextInt();
        l1:
        while (t-- > 0) {
            int n = next.nextInt();

            ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
            int[] subTreeSize = new int[n + 1];
            int[] inTime = new int[n + 1], outTime = new int[n + 1];

            for (int i = 0; i <= n; i++) {
                lists.add(new ArrayList<>());
            }

            int[] neighbours = new int[n + 1];

            int p = 1;
            for (int i = 1; i < n; i++) {
                int v = next.nextInt();
                int u = next.nextInt();
                lists.get(v).add(u);
                lists.get(u).add(v);
            }
            int res = 0;
            int first = 0, second = 0;
            for (int i = 1; i <= n; i++) {
                if (lists.get(i).size() >= lists.get(first).size()) {
                    second = first;
                    first = i;
                } else {
                    if (lists.get(i).size() >= lists.get(second).size()) {
                        second = i;
                    }
                }
            }
//            System.out.println(lists);
            int max1= lists.get(first).size();
            int max2 = lists.get(second).size();
//            System.out.println(first  +" "+ second);
            ArrayList<ArrayList<Integer>> tem = deepCopy(lists);
            removeNodeEdges(tem, first);
//            System.out.println(tem);
            int f1 = findMaxDegree(tem);
            tem = deepCopy(lists);
            removeNodeEdges(tem, second);
//            System.out.println(tem);
            int f2 = findMaxDegree(tem);
//            ArrayList<Integer> first = lists.get(0), sec = lists.get(1);

            System.out.println(Math.max(max1 + f1 - 1, max2 + f2 - 1));
        }
    }

    private static ArrayList<ArrayList<Integer>> deepCopy(ArrayList<ArrayList<Integer>> original) {
        ArrayList<ArrayList<Integer>> copy = new ArrayList<>();
        for (ArrayList<Integer> list : original) {
            copy.add(new ArrayList<>(list));
        }
        return copy;
    }

    // Remove all edges connected to the given node
    private static void removeNodeEdges(ArrayList<ArrayList<Integer>> adjList, int node) {
        int ct = 0;
        for (ArrayList<Integer> neighbors : adjList) {
            if (ct == node){
                neighbors.clear();
                ct++;
                continue;
            }
            neighbors.removeIf(e -> e == node);
            ct++;
        }
    }

    // Find the maximum degree of any node in the adjacency list
    private static int findMaxDegree(ArrayList<ArrayList<Integer>> adjList) {
        int maxDegree = 0;
        for (ArrayList<Integer> neighbors : adjList) {
            maxDegree = Math.max(maxDegree, neighbors.size());
        }
        return maxDegree;
    }
    // Depth-First Search to count valid paths
    public static void dfs(int currentNode, int parent, ArrayList<ArrayList<Integer>> adjacencyList, int[] size, int[] in, int[] out) {
        size[currentNode] = 1;
        // Flag to check if current node is a leaf
        boolean isLeaf = true;

        // Traverse all connected nodes
        for (int neighbor : adjacencyList.get(currentNode)) {
            if (neighbor != parent) {
                isLeaf = false; // Not a leaf as it has a child
                dfs(neighbor, currentNode, adjacencyList, size, in, out);
                size[currentNode] += size[neighbor];
            }
        }
    }

    public static int[] shortestDistanceToLeaf(int n, ArrayList<ArrayList<Integer>> adj) {
        int[] dist = new int[n + 1];
        Arrays.fill(dist, -1);  // -1 indicates that the vertex has not been visited.
        Queue<Integer> queue = new LinkedList<>();

        // Special case: if the tree contains only one node, it is itself a leaf.
        if (n == 1) {
            dist[1] = 0;
            return dist;
        }

        // Identify all leaf nodes.
        // A vertex is a leaf if it has 0 or 1 neighbor.
        // (Typically, in a connected tree, leaves will have exactly 1 neighbor.)
        for (int i = 1; i <= n; i++) {
            if (adj.get(i).size() <= 1) {
                dist[i] = 0;
                queue.offer(i);
            }
        }

        // Multi-source BFS: propagate distances from all leaves simultaneously.
        while (!queue.isEmpty()) {
            int current = queue.poll();
            for (int neighbor : adj.get(current)) {
                if (dist[neighbor] == -1) {  // Not visited yet.
                    dist[neighbor] = dist[current] + 1;
                    queue.offer(neighbor);
                }
            }
        }
        return dist;
    }

    static void printTreeLevels(ArrayList<ArrayList<Integer>> graph, int root, int n) {
        Queue<Integer> queue = new LinkedList<>();
        boolean[] visited = new boolean[n];

        queue.add(root);
        visited[root] = true;

        int level = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            System.out.print("Level " + level + ": ");

            for (int i = 0; i < size; i++) {
                int node = queue.poll();
                System.out.print(node + " ");

                for (int neighbor : graph.get(node)) {
                    if (!visited[neighbor]) {
                        visited[neighbor] = true;
                        queue.add(neighbor);
                    }
                }
            }
            System.out.println();
            level++;
        }
    }

    private static boolean isAncestor(int x, int y, int[] in, int[] out) {
        return in[x] <= in[y] && out[x] >= out[y];
    }


    public static int lowerBound(ArrayList<Integer> arr, long target, int start, int end) {
        int left = start, right = end;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr.get(mid) < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return left;
    }

    public static class FastReader {
        BufferedReader br;
        StringTokenizer st;

        public FastReader() {
            br = new BufferedReader(
                    new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        String nextLine() {
            String str = "";
            try {
                if (st.hasMoreTokens()) {
                    str = st.nextToken("\n");
                } else {
                    str = br.readLine();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
}