Sushi for Two

Title description:
Given a sequence of length n consisting of 1 and 2, ask you the longest continuous subsequence consisting of equal numbers of 1 and 2 and all 1s connected together and all 2s connected together.
The first line of Input
is a number n (2≤n≤100000), and the next line is n numbers (only including 1, 2).
Output
outputs the length of the longest substring that meets the requirements.
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

Idea:
For this question, we can only find out how many identical numbers there are in each small segment, and then traverse to find the smallest repeated value between adjacent two, and find out in all adjacent minimum values The largest repeated value is the largest repeated value he requested,
the above code:

#include <iostream>
#include <cstdio>

using namespace std;

const int manx = 100010;
int n,A[manx],j,ans = 1;
int B[manx],maxn = -0x3f3f3f,mixn = 0x3f3f3f;

int main () {
    
    
	cin >> n;
	for (int i = 1;i <= n;i++) {
    
    
		cin >> A[i];
		if(i!=1&&A[i] == A[i-1])//第一个不求重复值,因为计数变量ans初始值为1
			ans++;
		else if(i!=1&&A[i]!=A[i-1] ){
    
    //如果发现不相等的值,就存,然后把ans置为1
			B[++j] = ans;
			ans = 1;
		}
		if(i == n)//如果是最后一个也要将他的重复值存进去
			B[++j] = ans;
	}
	for(int i = 1;i <= j;i++) {
    
    
		mixn = min(B[i],B[i-1]);//找出相邻两个子串最小的个数
		maxn = max(maxn,mixn);//找出两个最小子串中最大的那个
	}
	cout << maxn*2 << endl;//得到结果乘于2即最终结果
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_48627750/article/details/119535110