最长和谐连续子序列
#include<bits/stdc++.h>
#define rep(i,a,n) for(int i=a;i<=n;i++)
#define per(i,n,a) for(int i=n;i>=a;i--)
using namespace std;
typedef long long ll;
const int maxn=5010;//数组所开最大值
const int mod=1e9+7;//模
const int inf=0x3f3f3f3f;//无穷大
int main()
{
int nums[20010];
int n = 0;
char c;
while((c=getchar())!='\n')
{
if(c>='0'&&c<='9')
{
ungetc(c,stdin);
cin>>nums[n++];
}
}
if(n == 1)
{
cout << 0 << endl;
return 0;
}
int i = 0;
int j = 1;
int res = 0;
int maxx = nums[0];
int minn = nums[0];
while(i < n && j < n)
{
if((abs(maxx - nums[j]) <= 1) && (abs(minn - nums[j]) <= 1)) ///2 2 3 4 3 2
{ minn = min(minn,nums[j]);
maxx = max(maxx,nums[j]);
//cout << "max:" << maxx << " minn:" << minn << endl;
//cout << "i:" << i <<" j:" << j <<endl;
//cout << "======" <<endl;
if(maxx - minn != 0)
res = max(res,j - i);
j ++;
}
else
{
if(maxx - minn == 1) // 5 12 9 9 9 9 9 9 9 9 9 9
res = max(res,j - i);
i ++;
j = i + 1;
maxx = nums[i];
minn = nums[i];
}
}
if(maxx - minn == 1) /// 2222
res = max(res,j - i);
cout <<res << endl;
return 0;
}
查看21道真题和解析