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: 905 ms):
import java.io.*;
import java.util.*;

public class RemoveExactlyTwo {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(System.out);

        int tc = Integer.parseInt(br.readLine());

        while (tc-- > 0) {
            int N = Integer.parseInt(br.readLine());

            // if (N <)

            ArrayList<Integer>[] adj = new ArrayList[N];
            HashMap<Integer, Integer> degCnt = new HashMap<>();

            for (int i = 0; i < N; i++) {
                adj[i] = new ArrayList<>(); 
            }

            for (int i = 0; i < N-1; i++) {
                String s = br.readLine();
                StringTokenizer st1 = new StringTokenizer(s);

                int a = Integer.parseInt(st1.nextToken()) - 1;
                int b = Integer.parseInt(st1.nextToken()) - 1;

                adj[a].add(b);
                adj[b].add(a);
            }

            for (int i = 0; i < N; i++) {
                int deg = adj[i].size();
                degCnt.put(i, deg);
            }
            int res = 1;
            ArrayList<Integer> maxKeys = getBiggestKeys(degCnt);

            if (maxKeys.size() == 1) {
                res += degCnt.get(maxKeys.get(0)) - 1;
                degCnt.remove(maxKeys.get(0));

                for (int n : adj[maxKeys.get(0)]) {
                    degCnt.put(n, degCnt.get(n)-1);
                }

                res += degCnt.get(getBiggestKeys(degCnt).get(0)) - 1;
            } else {
                int max = degCnt.get(maxKeys.get(0));
                boolean done = false;
                for (int key : maxKeys) {
                    ArrayList<Integer> affected = adj[key];
                    int affectedCount = 0;
                    for (int v : affected) {
                        if (degCnt.get(v) == max) {
                            affectedCount++;
                        }
                    }

                    if (maxKeys.size() - affectedCount > 1) {
                        res = max * 2 - 1;
                        done = true;
                        break;
                    }
                }

                if (!done) {
                    res = max*2-2;
                }
            }

            pw.println(res);
        }

        pw.close();
    }

    static ArrayList<Integer> getBiggestKeys(HashMap<Integer, Integer> hm) {
        ArrayList<Integer> maxKeys = new ArrayList<>();
        for (Map.Entry<Integer, Integer> entry : hm.entrySet()) {
            int key = entry.getKey();
            int val = entry.getValue();

            if (maxKeys.size() == 0 || val >= hm.get(maxKeys.get(0))) {
                if (maxKeys.size() == 0 || val > hm.get(maxKeys.get(0))) {
                    maxKeys.clear();
                    maxKeys.add(key);
                } else {
                    maxKeys.add(key);
                }
            }
        }
        return maxKeys;
    }
}