Problem: 2063C - Remove Exactly Two
Language: java

Solution 1 (runtime: 1515 ms):
import java.util.*;
import java.lang.*;
import java.io.*;
public class Codechef
    {
	static FastScanner fs = null;
	static int res;
	static ArrayList<Set<Integer>> list;
	static int co[];
	static Map<Integer,Integer> map;
	static TreeSet<Integer> ts;
	static int inf = (int)1e8;
	static boolean vis[];
	public static void main(String[] args) {
		fs = new FastScanner();

		PrintWriter out = new PrintWriter(System.out);
		int t = fs.nextInt();
        while(t-->0){
            list = new ArrayList<>();
            int n = fs.nextInt();
            co = new int[n+1];
            ts = new TreeSet<>();
            map = new HashMap<>();
            vis = new boolean[n+1];
            Arrays.fill(vis,false);
            for(int i = 0;i<=n;i++){
                Set<Integer> se = new HashSet<>();
                list.add(se);
            }
            for(int i = 1;i<n;i++){
                int u = fs.nextInt();
                int v = fs.nextInt();
                list.get(u).add(v);
                list.get(v).add(u);
                co[u]+=1;
                co[v]+=1;
            }
            for(int i = 1;i<=n;i++){
                int num = co[i];
                ts.add(num);
                if(map.get(num)==null){
                    map.put(num,1);
                }
                else{
                    map.replace(num,1+map.get(num));
                }
            }
            res = 0;
            //System.out.println("---------");
            dfs(1,-1);
            //out.println(res+" ------ ");
            dfs2(1);
           // res = Math.min(res,n-2);
            out.println(res);
        }
		out.close();
	}
	static void dfs2(int node){
	    vis[node] = true;
	    int ans1 = co[node];
	        map.replace(ans1,-1+map.get(ans1));
	        if(map.get(ans1)==0){
	            ts.remove(ans1);
	        }
	    for(Integer p:list.get(node)){
	        int nu = co[p];
	        //System.out.println(p+" -- "+node+" -- "+nu+" --- "+map.get(nu));
	        
	        map.replace(nu,-1+map.get(nu));
	        if(map.get(nu)==0){
	            ts.remove(nu);
	        }
	    }
	    int re = ans1;
	    if(ts.floor(inf)!=null){
	        re+=ts.floor(inf);
	    }
	   // else{
	   //     re-=1;
	   // }
	   
	   
	   map.replace(ans1,+1+map.get(ans1));
	        ts.add(ans1);
	    for(Integer p:list.get(node)){
	        int nu = co[p];
	        map.replace(nu,+1+map.get(nu));
	        ts.add(nu);
	    }
	    //System.out.println(node+" --- "+re+" -- "+ans1);
	    res = Math.max(res,re-1);
	    for(Integer p:list.get(node)){
	        if(!vis[p]){
	            dfs2(p);
	        }
	    }
	     
	}
	static int dfs(int node,int par){
	    for(Integer p:list.get(node)){
	        if(p==par)
	        continue;
	        dfs(p,node);
	        if(par!=-1){
	            res = Math.max(res,co[node]+co[par]-2); 
	        }
	    }
	    
	    //System.out.println(d1+" -- "+d2+" --- "+node+" -- "+par+" -- "+sz);
	    return 0;
	}
	static void sort(int[] a) {
		ArrayList<Integer> l=new ArrayList<>();
		for (int i:a) l.add(i);
		Collections.sort(l);
		for (int i=0; i<a.length; i++) a[i]=l.get(i);
	}
	static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
		String next() {
			while (!st.hasMoreTokens())
				try {
					st=new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			return st.nextToken();
		}
		
		int nextInt() {
			return Integer.parseInt(next());
		}
		int[] readArray(int n) {
			int[] a=new int[n];
			for (int i=0; i<n; i++) a[i]=nextInt();
			return a;
		}
		long nextLong() {
			return Long.parseLong(next());
		}
		double nextDouble() {
			return Double.parseDouble(next());
		}
	}
}

Solution 2 (runtime: 1296 ms):
import java.io.*;
import java.util.*;

public class RemoveExactlyTwo {

    static int mod = 1000000007;

    public static void main(String[] args) throws IOException {

        FastReader reader = new FastReader();
        FastWriter writer = new FastWriter();

        int numTests = reader.readSingleInt();
        for (int t = 0; t < numTests; t++) {
            int n = reader.readSingleInt();

            Node[] nodes = new Node[n];
            for (int i = 0; i < n; i++) {
                nodes[i] = new Node(i);
            }

            for (int i = 0; i < n - 1; i++) {
                int[] uv = reader.readIntArray(2);
                int u = uv[0] - 1;
                int v = uv[1] - 1;
                nodes[u].children.add(nodes[v]);
                nodes[v].children.add(nodes[u]);
            }

            var largest = new HashSet<Node>();
            int max = 0;
            for (int i = 0; i < n; i++) {
                if (max == nodes[i].children.size()) {
                    largest.add(nodes[i]);
                } else if (max < nodes[i].children.size()) {
                    largest.clear();
                    largest.add(nodes[i]);
                    max = nodes[i].children.size();
                }
            }

            var toppers = new ArrayList<>(largest);
            var top = toppers.get(0);

            boolean allChildren = true;
            for (int i = 1; i < toppers.size(); i++) {
                if (!top.children.contains(toppers.get(i))) {
                    allChildren = false;
                    break;
                }
            }
            if (allChildren && toppers.size() > 1) {
                top = toppers.get(1);
            }


            for (var child : top.children) {
                child.children.remove(top);
            }
            top.children.clear();

            max = 0;
            for (int i = 0; i < n; i++) {
                if (nodes[max].children.size() < nodes[i].children.size()) {
                    max = i;
                }
            }

            for (var child : nodes[max].children) {
                child.children.remove(nodes[max]);
            }
            nodes[max].children.clear();

            var count = 0;
            var seen = new HashSet<Node>();
            for (int i = 0; i < n; i++) {
                if (seen.contains(nodes[i])) {
                    continue;
                }

                count++;

                seen.add(nodes[i]);
                var stack = new Stack<Node>();

                stack.push(nodes[i]);
                while (!stack.isEmpty()) {
                    top = stack.pop();
                    for (var child : top.children) {
                        if (seen.contains(child)) {
                            continue;
                        }
                        seen.add(child);
                        stack.push(child);
                    }
                }
            }

            writer.writeSingleInteger(count - 2);
        }
    }

    public static class Node {
        int id;
        Set<Node> children = new HashSet<>();

        Node(int id) {
            this.id = id;
        }
    }


    public static void mergeSort(int[] a, int n) {
        if (n < 2) {
            return;
        }
        int mid = n / 2;
        int[] l = new int[mid];
        int[] r = new int[n - mid];

        for (int i = 0; i < mid; i++) {
            l[i] = a[i];
        }
        for (int i = mid; i < n; i++) {
            r[i - mid] = a[i];
        }

        mergeSort(l, mid);
        mergeSort(r, n - mid);

        merge(a, l, r, mid, n - mid);
    }


    public static void merge(int[] a, int[] l, int[] r, int left, int right) {

        int i = 0, j = 0, k = 0;
        while (i < left && j < right) {
            if (l[i] <= r[j]) {
                a[k++] = l[i++];
            } else {
                a[k++] = r[j++];
            }
        }
        while (i < left) {
            a[k++] = l[i++];
        }
        while (j < right) {
            a[k++] = r[j++];
        }
    }


    public static class FastReader {

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer tokenizer;


        public int readSingleInt() throws IOException {
            return Integer.parseInt(reader.readLine());
        }

        public int[] readIntArray(int numInts) throws IOException {
            int[] nums = new int[numInts];
            tokenizer = new StringTokenizer(reader.readLine());
            for (int i = 0; i < numInts; i++) {
                nums[i] = Integer.parseInt(tokenizer.nextToken());
            }
            return nums;
        }

        public long[] readLongArray(int numInts) throws IOException {
            long[] nums = new long[numInts];
            tokenizer = new StringTokenizer(reader.readLine());
            for (int i = 0; i < numInts; i++) {
                nums[i] = Long.parseLong(tokenizer.nextToken());
            }
            return nums;
        }

        public String readString() throws IOException {
            return reader.readLine();
        }

    }


    public static class FastWriter {

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));


        public void writeSingleInteger(int i) throws IOException {
            writer.write(Integer.toString(i));
            writer.newLine();
            writer.flush();
        }

        public void writeSingleLong(long i) throws IOException {
            writer.write(Long.toString(i));
            writer.newLine();
            writer.flush();
        }

        public void writeIntArrayWithSpaces(int[] nums) throws IOException {
            for (int i = 0; i < nums.length; i++) {
                writer.write(nums[i] + " ");
            }
            writer.newLine();
            writer.flush();
        }

        public void writeLongArrayWithSpaces(long[] nums) throws IOException {
            for (int i = 0; i < nums.length; i++) {
                writer.write(nums[i] + " ");
            }
            writer.newLine();
            writer.flush();
        }

        public void writeIntArrayListWithSpaces(ArrayList<Integer> nums) throws IOException {
            for (int i = 0; i < nums.size(); i++) {
                writer.write(nums.get(i) + " ");
            }
            writer.newLine();
            writer.flush();
        }

        public void writeIntArrayWithoutSpaces(int[] nums) throws IOException {
            for (int i = 0; i < nums.length; i++) {
                writer.write(Integer.toString(nums[i]));
            }
            writer.newLine();
            writer.flush();
        }

        public void writeString(String s) throws IOException {
            writer.write(s);
            writer.newLine();
            writer.flush();
        }

    }


}