题目链接:三回文序列 - 题目 - Daimayuan Online Judge
视频题解:【算法camp】【每日一题】Namomo Spring Camp Div2 第44天题解(枚举,前缀和)dls讲题!!_哔哩哔哩_bilibili 思路很巧妙的一题,考虑把数组分为三部分:左边,右边和中间。使得左边和右边部分的当前枚举数字个数相同,然后取中间其他数字的最大数量,但是要主要特判左右指针重合的情况。详见题解。
#include <bits/stdc++.h>
#define int long long
#define debug cout<<"!!!"<<endl;
#define FOR(i, a, b) for (int i = (a); i <= (b); i++)
#define ROF(i, a, b) for (int i = (a); i >= (b); i--)
#define pii pair<int,int>
#define ls p<<1
#define rs p<<1|1
using namespace std;
const int N = 2e5+5;
int n,a[N],sum[30][N];
inline void solve(){
cin>>n; FOR(i,1,n) cin>>a[i];
FOR(i,1,26) FOR(j,1,n) sum[i][j]=sum[i][j-1]+(a[j]==i);
int ans = 0; //记录答案
FOR(c1,1,26){
int l=0,r=n+1,nl=0,nr=0; //左右指针
FOR(cnt,1,n){
while(nl<cnt && l<r) l++, nl+=(a[l]==c1); //移动指针,维护数量
while(nr<cnt && l<r) r--, nr+=(a[r]==c1);
if(nl!=cnt || nr!=cnt) break; //无法满足,结束
FOR(c2,1,26){
if(l<r) ans = max(ans, cnt*2+sum[c2][r-1]-sum[c2][l]);
else ans = max(ans,cnt*2-1);
}
}
}
cout<<ans<<'\n';
}
signed main(){
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int T; cin>>T; while(T--) solve();
}