题目
东东和他的女朋友(幻想的)去寿司店吃晚餐(在梦中),他发现了一个有趣的事情,这家餐厅提供的 n 个的寿司被连续的放置在桌子上 (有序),东东可以选择一段连续的寿司来吃
东东想吃鳗鱼,但是东妹想吃金枪鱼。核 平 起 见,他们想选择一段连续的寿司(这段寿司必须满足金枪鱼的数量等于鳗鱼的数量,且前一半全是一种,后一半全是另外一种)我们用1代表鳗鱼,2代表金枪鱼。
比如,[2,2,2,1,1,1]这段序列是合法的,[1,2,1,2,1,2]是非法的。因为它不满足第二个要求。
东东希望你能帮助他找到最长的一段合法寿司,以便自己能吃饱。
Input
输入:
第一行:一个整数n(2≤n≤100000),寿司序列的长度。
第二行:n个整数(每个整数不是1就是2,意义如上所述)
Output
输出:一个整数(代表东东可以选择的最长的一段连续的且合法的寿司)
Examples
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
思路
利用滑动窗口的思路
len1记录左半段的长度,len2记录右半段的长度,并根据shousi[r+1]和cnt判断所处的不同情况,进行len1、len2,cnt,max的更新
代码
#include<iostream>
using namespace std;
const int maxn=1e5+10;
int shousi[maxn];
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++)
cin>>shousi[i];
int l=0,r=0,len1=1,len2=0,cnt=1,max=0;
while(r<n)
{
if(shousi[r+1]==shousi[r]&&len2<len1)
{
r++;
if(cnt==1)
len1++;
else
len2++;
}
else if(shousi[r+1]==shousi[r]&&len2==len1)
{
int len=r-l+1;
if(max<len)
max=len;
r++;
while(shousi[l]!=shousi[r])
l++;
len1=len2+1;
len2=0;
cnt=1;
}
else if(shousi[r+1]!=shousi[r])
{
if(cnt==2)
{
int len=2*len2;
if(max<len)
max=len;
while(shousi[l]!=shousi[r])
l++;
r++;
len1=len2;
len2=1;
}
else if(cnt==1)
{
r++;
len2++;
cnt=2;
}
}
}
cout<<max<<endl;
return 0;
}