Problem: 2063C - Remove Exactly Two
Language: java

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

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;
    }
}