天天看點

codeforces 602B

題意:有n個數字,找出最長的一段連續的序列,要求這個序列的最大數和最小數相差不能大于1

分析:一段序列,可能有的會重複,那麼就壓縮一下,把連續的相同的數字壓縮為一個,并記錄數字個數,這樣在從頭走一遍就好了。

/*

Sample test(s) Input

5
1 2 3 3 2
      

Output

4
      

Input

11
5 4 5 5 6 7 8 8 8 7 6
      

Output

5      

*/

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
#define maxn 100002
#define INF 0x3f3f3f3f
const int mod=1e9+7;
struct point{
    int x,y;
}a[maxn];
int main()
{
    int n,t,num=1,cnt=0,x;
    scanf("%d",&n);
    scanf("%d",&x);
    for(int i=1;i<n-1;i++){
        scanf("%d",&t);
        if(t==x){
            num++;
        }
        else{
            a[cnt].y=num;
            num=1;
            a[cnt++].x=x;
            x=t;
        }
    }
    scanf("%d",&t);
    if(x==t)a[cnt].y=num+1,a[cnt++].x=x;
    else{
        a[cnt].x=x,a[cnt++].y=num;
        a[cnt].x=t,a[cnt++].y=1;
    }
   // cout<<a[0].x<<a[0].y<<endl;
  //  cout<<a[1].x<<a[1].y<<endl;
    int ans=a[0].y,sum=a[0].y;
    if(cnt==2){
        if(a[0].x==a[1].x||a[0].x==a[1].x+1||a[0].x==a[1].x-1){
            ans=a[0].y+a[1].y;
        }
        else{
            ans=max(a[0].y,a[1].y);
        }
    }
    else if(cnt>2)sum=a[0].y+a[1].y;
    for(int i=2;i<cnt;i++){
        if(a[i].x!=a[i-2].x&&a[i].x!=a[i-1].x){
            ans=max(ans,sum);
            if(a[i].x==a[i-1].x+1||a[i].x==a[i-1].x-1){
                sum=a[i-1].y+a[i].y;
            }
            else{
                sum=a[i].y;
            }
        }
        else{
            sum+=a[i].y;
        }
    }
    ans=max(ans,sum);
    printf("%d\n",ans);
}