Problem: 2063C - Remove Exactly Two
Language: java

Solution 1 (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;
    }
}

Solution 2 (runtime: 1421 ms):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class RemoveExactlyTwo {

    public static int[][] dfs(int src, int par, List<List<Integer>> arr) {

        int[][] new_components = new int[3][2];

        int first_max = 0, second_max = 0;

        for (int v : arr.get(src)) {
            if (par == v) continue;

            int[][] components = dfs(v, src, arr);

            new_components[0][0] = Math.max(new_components[0][0], components[0][0]);
            new_components[0][1] = Math.max(new_components[0][1], components[0][1]);

            new_components[1][0] = Math.max(new_components[1][0], Math.max(components[1][0], components[1][1]));
            new_components[1][1] = Math.max(new_components[1][1], components[0][0] + arr.get(src).size());
            new_components[1][1] = Math.max(new_components[1][1], components[0][1] + arr.get(src).size() - 1);
            
            new_components[2][0] = Math.max(new_components[2][0], Math.max(components[2][0], components[2][1]));
            new_components[2][1] = Math.max(new_components[2][1], components[1][0] + arr.get(src).size());
            new_components[2][1] = Math.max(new_components[2][1], components[1][1] + arr.get(src).size() - 1);

            if (first_max < components[1][0] || first_max < components[1][1]) {
                second_max = first_max;
                first_max = Math.max(components[1][0], components[1][1]);
            } else if (second_max < components[1][0] || second_max < components[1][1]) {
                second_max = Math.max(components[1][0], components[1][1]);
            }
        }

        if (arr.get(src).isEmpty()) {

            new_components[0][0] = 1;
            new_components[0][1] = Integer.MIN_VALUE/2;

            new_components[1][0] = Integer.MIN_VALUE/2;
            new_components[1][1] = 0;

            new_components[2][0] = Integer.MIN_VALUE/2;
            new_components[2][1] = Integer.MIN_VALUE/2;
            
        } else {
            new_components[2][0] = Math.max(first_max + second_max, new_components[2][0]);
        }

        return new_components;
    }
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int t =  Integer.parseInt(br.readLine());

        while(t-- > 0) {

           int n = Integer.parseInt(br.readLine());
           
           int edges = n - 1;

           List<List<Integer>> arr = new ArrayList<>();

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

           while (edges-- > 0) {
                int[] e = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();

                arr.get(e[0] - 1).add(e[1] - 1);
                arr.get(e[1] - 1).add(e[0] - 1);
           }

           int[][] components = dfs(0, -1, arr);

           System.out.println(Math.max(components[2][0], components[2][1]) - 1);

        }
    }
}