样例:
Input
7
2 2 2 1 1 2 2
Output
4
Input
6
1 2 1 2 1 2
Output
2
Input
9
2 2 1 1 1 2 2 2 2
Output
6
这题用滑窗的思想解决。具体细节和注释都在代码里。
#include<iostream>
using namespace std;
int a[100100];
int number[3];
int n;
int main()
{
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
int left=0,right=0;
for(int i=0;i<3;i++)
{
number[i]=0;
}
number[a[left]]++;
int temp=a[left];//temp存储的是当前的寿司种类
int maxx=0;//存储当前最长序列长度
while(right<n)
{
if(right+1<n)
{
right++;
number[a[right]]++;
if(a[right]!=temp)//寿司的种类变化了
{
temp=a[right];
if(a[left]==a[right])//例如2 2 2 1 1 2 2,a[left]=a[right]时left=0,right=5,那么最左边的那段2序列就得舍弃掉,所以number[2]=1,left也相应变化
{
number[a[left]]=1;
left=right-1;
}
else
{
if(number[a[right]]<=number[a[left]])//例如2 2 2 1 1 2 2,比如left=0,right=3,此时a[left]=2,a[right]=1,只有这种情况下才会进入这个else
{
if(maxx<2*number[a[right]])
{
maxx=2*number[a[right]];
}
}
}
}
else
{
if(number[a[right]]<=number[a[left]]&&a[left]!=a[right])//2 2 2 1 1 2 2,例如left=0,right从3变到4
{
if(maxx<2*number[a[right]])
{
maxx=2*number[a[right]];
}
}
}
}
else
{
break;
}
}
cout<<maxx;
}