The only difference between easy and hard versions is constraints.
You are given a sequence aa consisting of nn positive integers.
Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are aa and bb, aa can be equal bb) and is as follows: [a,a,…,ax,b,b,…,by,a,a,…,ax][a,a,…,a⏟x,b,b,…,b⏟y,a,a,…,a⏟x]. There x,yx,y are integers greater than or equal to 00. For example, sequences [][], [2][2], [1,1][1,1], [1,2,1][1,2,1], [1,2,2,1][1,2,2,1] and [1,1,2,1,1][1,1,2,1,1] are three block palindromes but [1,2,3,2,1][1,2,3,2,1], [1,2,1,2,1][1,2,1,2,1] and [1,2][1,2] are not.
Your task is to choose the maximum by length subsequence of aa that is a three blocks palindrome.
You have to answer tt independent test cases.
Recall that the sequence tt is a a subsequence of the sequence ss if tt can be derived from ss by removing zero or more elements without changing the order of the remaining elements. For example, if s=[1,2,1,3,1,2,1]s=[1,2,1,3,1,2,1], then possible subsequences are: [1,1,1,1][1,1,1,1], [3][3] and [1,2,1,3,1,2,1][1,2,1,3,1,2,1], but not [3,2,3][3,2,3] and [1,1,1,1,2][1,1,1,1,2].
Input
The first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases. Then tt test cases follow.
The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤2001≤ai≤200), where aiai is the ii-th element of aa. Note that the maximum value of aiai can be up to 200200.
It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).
Output
For each test case, print the answer — the maximum possible length of some subsequence of aa that is a three blocks palindrome.
Example
input
6
8
1 1 2 2 3 2 1 1
3
1 3 3
4
1 10 10 1
1
26
2
2 1
3
1 1 1
output
7
2
4
1
1
3
给你n个数,,找出最长的特殊回文子序列。
用 vector 记录每个数出现的位置,固定两端的数,求中间出现的数的数量的最大值,可以用二分快速求得:
比如下面的一组数(下标从1开始):
1 1 2 2 3 2 1 1
第一对1出现的位置, l=1,r=7,,用upper_bound函数求得第一个大于l的2的位置是0,第一个大于r的2的位置是3,,(upper_bound函数找不到就返回end()),,所以ans=2*1+3-0=5;
第二对1出现的位置, l=1,r=7,,用upper_bound函数求得第一个大于l的2的位置是0,第一个大于r的2的位置是3,,(upper_bound函数找不到就返回end()),,所以ans=2*2+3-0=5;
以此类推,,每一次循环都更新答案。。
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,k,t;
cin>>t;
while(t--){
vector<int>v[205];
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>k;
v[k].push_back(i);
}
int ans=0;
for(int i=1;i<=200;i++)
{
int num=v[i].size();
if(num==0)
continue;
ans=max(ans,num);
for(int j=0;j<v[i].size()/2;j++)
{
int l=v[i][j],r=v[i][num-j-1];
for(int k=1;k<=200;k++)
{
if(k==i) continue;
int pos1=upper_bound(v[k].begin(),v[k].end(),l)-v[k].begin();
int pos2=upper_bound(v[k].begin(),v[k].end(),r)-v[k].begin();
//cout<<pos1<<" "<<pos2<<endl;
ans=max(ans,(j+1)*2+pos2-pos1);
}
}
}
cout<<ans<<endl;
}
return 0;
}