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: 1843 ms):
// https://codeforces.com/problemset/problem/2063/C

import java.util.*;

public class Main
{
    private static void dfs_dp (int v, int p, final ArrayList<Integer>[] tree, int[] dp)
    {
        for (int to : tree[v])
        if (to != p)
        {
            dfs_dp(to, v, tree, dp);

            dp[v] = Math.max(dp[v], Math.max(dp[to], tree[to].size()));
        }
    }

    private static int dfs_ans (int v, int p, final ArrayList<Integer>[] tree, final int[] dp)
    {
        int ans = 0;

        for (int to : tree[v])
        if (to != p)
            ans = Math.max(ans, dfs_ans(to, v, tree, dp));

        for (int to : tree[v])
        if (to != p)
            ans = Math.max(ans, tree[v].size()-1 + Math.max(tree[to].size() - 1, dp[to]));
        
        int maxi = -1;

        for (int to : tree[v])
        if (to != p)
        {
            int cur = Math.max(tree[to].size(), dp[to]);

            if (maxi != -1)
                ans = Math.max(ans, maxi + cur - 1);
            
            maxi = Math.max(maxi, cur);
        }

        return ans;
    }
    
    private static void solve (Scanner in)
    {
        int n = in.nextInt();

        ArrayList<Integer>[] tree = new ArrayList[n];

        for (int i = 0; i < n; i++)
            tree[i] = new ArrayList<Integer>();

        for (int i = 1; i < n; i++)
        {
            int u = in.nextInt() - 1;
            int v = in.nextInt() - 1;

            tree[u].add(v);
            tree[v].add(u);
        }

        int[] dp = new int[n];

        for (int i = 0; i < n; i++)
            dp[i] = 0;

        dfs_dp(0, -1, tree, dp);
        
        int ans = dfs_ans(0, -1, tree, dp);

        System.out.println(ans);
    }

    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);

        int t = in.nextInt();

        for (int test = 0; test < t; test++)
            solve(in);

        in.close();
    }
}