Week11 Assignment-D-Required Questions 11-4

topic

Dongdong and his girlfriend (fantasy) went to a sushi restaurant for dinner (in a dream). He discovered an interesting thing. The n pieces of sushi provided by this restaurant were placed on the table in succession (ordered) Dongdong can choose a continuous piece of sushi to eat.
Dongdong wants to eat eel, but Dongmei wants to eat tuna. For the sake of nuclear peace, they want to choose a continuous piece of sushi (this piece of sushi must satisfy that the number of tuna is equal to the number of eels, and the first half is all one type, and the second half is all another type) We use 1 for eel and 2 for tuna .
For example, the sequence [2,2,2,1,1,1] is legal, and [1,2,1,2,1,2] is illegal. Because it does not meet the second requirement.
Dongdong hopes that you can help him find the longest piece of legal sushi so that he can eat.

Input

enter:

The first line: an integer n (2≤n≤100000), the length of the sushi sequence.

The second line: n integers (each integer is either 1 or 2, meaning as described above)

Output

Output: an integer (representing the longest piece of continuous and legal sushi that Dongdong can choose)

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

Ideas

Using the idea of ​​sliding window,
len1 records the length of the left half, len2 records the length of the right half, and judges the different situations according to shousi[r+1] and cnt, and updates len1, len2, cnt, max

Code

#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;
}

Guess you like

Origin blog.csdn.net/alicemh/article/details/105892035