最长和谐连续子序列

图片说明

#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;
}
全部评论

相关推荐

2024-12-26 13:00
太原理工大学 Java
会飞的猿:简历没啥大问题啊,感觉是缺少了实习经历。多投投先找个中小厂过渡一下吧
点赞 评论 收藏
分享
2024-12-26 20:46
复旦大学 C++
国棉17厂丶小王:拿了offer的那个周末晚上去网吧通宵,去网吧不知道玩什么刷了lc的每日一题,然后试着第一次打开了三角洲行动,从此少了一个已经刷了700道题的lc用户,但是烽火地带多了一只🐭🐭
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务