题目描述:
给你长度为n的由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
思路:
对于这题我们只能求出每一小段的相同数有多少个,然后再遍历的去找出相邻两个之间最小的那个重复值,在找出所有相邻最小值里找出最大的那个重复值就是他要求的最大的重复值,
上代码:
#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;
}