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.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.List;
import java.util.Set;
import java.util.HashSet;

public class C {
	
	public static void main(String[] args) {
		FastScanner fs=new FastScanner();
		PrintWriter out=new PrintWriter(System.out);
		
        int T = fs.nextInt();
        for (int tt = 0; tt < T; tt++) {
            int n = fs.nextInt();
            if (n == 1) {
                out.println(0);
                continue;
            }
            Set<Integer>[] adjList = new HashSet[n+1];
            for (int i = 0; i <= n; i++) {
                adjList[i] = new HashSet<>();
            }
            List<Integer> maxVertices = new ArrayList<>();
            int maxNeighbour = Integer.MIN_VALUE;
            for (int i = 0; i < n-1; i++) {
                int u = fs.nextInt(), v = fs.nextInt();
                adjList[u].add(v);
                adjList[v].add(u);
                boolean flagu = false;
                boolean flagv = false;
                if (maxNeighbour < adjList[u].size()) {
                    maxNeighbour = adjList[u].size();
                    maxVertices = new ArrayList<>();
                    maxVertices.add(u);
                    flagu = true;
                }
                if (maxNeighbour < adjList[v].size()) {
                    maxNeighbour = adjList[v].size();
                    maxVertices = new ArrayList<>();
                    maxVertices.add(v);
                    flagv = true;
                }
                if (!flagu && maxNeighbour == adjList[u].size()) {
                    maxVertices.add(u);
                }
                if (!flagv && maxNeighbour == adjList[v].size()) {
                    maxVertices.add(v);
                }
            }
            
            int ans = Integer.MIN_VALUE;

            for (int i = 0; i < Math.min(2,maxVertices.size()); i++) {
                int maxNode = maxVertices.get(i);
                Set<Integer> maxNodeNeigh = adjList[maxNode];
                
                for (int j = 1; j <= n; j++) {
                    if (j != maxNode) {
                        if (maxNodeNeigh.contains(j)) {
                            ans = Math.max(ans, maxNodeNeigh.size() + adjList[j].size() - 2);
                        }
                        else {
                            ans = Math.max(ans, maxNodeNeigh.size() + adjList[j].size() - 1);
                        }
                    } 
                    
                }
            }
            out.println(ans);
        }
		out.close();
	}

	public static long binpowmod(long a, long b, long m) {
		a %= m;
		long result = 1L;
		while (b > 0) {
			if ((b & 1) == 1) {
				result = (result * a) % m;
			}
			a = (a * a) % m;
			b >>= 1;
		}
		return result;
	}

    public static long hash(String s) {
        int MOD = (int) (1e9 + 7);
        long value = 0;
        for (char c : s.toCharArray()) {
            value = (value * 31 + (c - 'a' + 1)) % MOD;
        }
        return value;
    }

    // this is for FLOOR DIVISION with NEGATIVE numerator
    public static long fDiv(long x, long y) {
        if (x >= 0) {
            return x/y;
        }
        else {
            return (x-y+1)/y;
        }
    }

    // change long to int accordingly
    public static long binomialCoeff(int n, int k)
    {
        long C[][] = new long[n + 1][k + 1];
        int i, j;

        // Calculate  value of Binomial
        // Coefficient in bottom up manner
        for (i = 0; i <= n; i++) {
            for (j = 0; j <= Math.min(i, k); j++) {
                // Base Cases
                if (j == 0 || j == i)
                    C[i][j] = 1;

                // Calculate value using
                // previously stored values
                else
                    C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
            }
        }

        return C[n][k];
    }

	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());
		}
	}
	
	 // GCD - Euclid's Algo by Modulo
    // log max(a,b)
    /* 
    public static int gcd(int a, int b) {
        if (a == 0) {
            return b;
        }
        return gcd(b % a, a);
    }
    */
	
	// Sieve of Eratosthenes
	/*
	boolean[] array = new boolean[length + 1];
 
	for (int i = 2; i * 2 <= length; i++) {
		if (array[i] == false) {
			for (int j = i; j <= length;j+= i) {
				//out.println(j);
				array[j] = true;
			}
		}
	}*/

	// Next permutation
	/*
	public static boolean nextPermutation(int[] ordering) {
 
 
		// If the given ordering set is empty
        // or contains only one element
        // next_permutation is not possible
        if (ordering.length <= 1)
            return false;
 
        int last = ordering.length - 2;
 
        // find the longest non-increasing suffix
        // and find the pivot
        while (last >= 0) {
            if (ordering[last] < ordering[last + 1]) {
                break;
            }
            last--;
        }
 
        // If there is no increasing pair
        // there is no higher order permutation
        if (last < 0)
            return false;
 
        int nextGreater = ordering.length - 1;
 
        // Find the rightmost successor to the pivot
        for (int i = ordering.length - 1; i > last; i--) {
            if (ordering[i] > ordering[last]) {
                nextGreater = i;
                break;
            }
        }
 
        // Swap the successor and the pivot
        swap(ordering, nextGreater, last);
 
        // Reverse the suffix
        reverse(ordering, last + 1, ordering.length - 1);
 
        // Return true as the next_permutation is done
        return true;
	}
 
	public static int[] swap(int ordering[], int left, int right)
    {
 
        // Swap the ordering
        int temp = ordering[left];
        ordering[left] = ordering[right];
        ordering[right] = temp;
 
        // Return the updated array
        return ordering;
    }
 
    // Function to reverse the sub-array
    // starting from left to the right
    // both inclusive
    public static int[] reverse(int ordering[], int left, int right)
    {
 
        // Reverse the sub-array
        while (left < right) {
            int temp = ordering[left];
            ordering[left++] = ordering[right];
            ordering[right--] = temp;
        }
 
        // Return the updated array
        return ordering;
    } */

    // KMP Algorithm
    // Compute LPS array
    // 0 >= arr[i], arr[i] <= i (array is 0-indexed)
    public static int[] computeLPS(String s) {
        int n = s.length();
        int[] arr = new int[n];
        for (int i = 1; i < n; i++) {
            int j = arr[i-1]; 
            while (j > 0 && s.charAt(i) != s.charAt(j)) {
                j = arr[j-1];
            }
            if (s.charAt(i) == s.charAt(j)) {
                j++;
            }
            arr[i] = j;
        }
        return arr;
    }
}