Problem: The only difference between easy and hard versions is constraints.
You are given a sequence consisting of positive integers.
Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are and , can be equal ) and is as follows: . There are integers greater than or equal to . For example, sequences , , , , and are three block palindromes but , and are not.
Your task is to choose the maximum by length subsequence of that is a three blocks palindrome.
You have to answer independent test cases.
Recall that the sequence is a a subsequence of the sequence if can be derived from by removing zero or more elements without changing the order of the remaining elements. For example, if , then possible subsequences are: , and , but not and .
Input Format: The first line of the input contains one integer () — the number of test cases. Then test cases follow.
The first line of the test case contains one integer () — the length of . The second line of the test case contains integers (), where is the -th element of . Note that the maximum value of can be up to .
It is guaranteed that the sum of over all test cases does not exceed ().
Output Format: For each test case, print the answer — the maximum possible length of some subsequence of that is a three blocks palindrome.