题目链接:
https://leetcode-cn.com/contest/weekly-contest-120/problems/longest-turbulent-subarray/
滑动窗口法(参考 力扣阅读)
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
//滑动窗口法
int compare_(int a,int b){
if(a>b)
return -1;
else if(a<b)
return 1;
else return 0;
}
//数组
int maxTurbulenceSize(vector<int>& A){
int N=A.size();
int ans=1;
int anchor=0;
//假设给定数组为 A = [9,4,2,10,7,8,8,1,9]。
//那么符号序列就是 [1,1,-1,1,-1,0,-1,1]。
//它可以被划分成的块为 [1], [1,-1,1,-1], [0], [-1,1]。
for(int i=1;i<N;i++){
int c;
c=compare_(A[i-1],A[i]);
if(i==N-1||c*compare_(A[i],A[i+1])!=-1){
//扫描到一个块的末尾(符号序列已经结束 或 不再交替)
//就记录下这个块的答案,将其作为一个候选答案,然后设置下一个元素作为下一个块的开头
if(c!=0) ans=max(ans,i-anchor+1);
//初始块的答案 记录下这个块的答案
anchor=i;//设置下一个元素作为下一个块的开头
}
}
return ans;
}
int main()
{
int A[]={9,4,2,10,7,8,8,1,9};
vector<int> B;
B.insert(B.begin(),A,A+9);
cout << maxTurbulenceSize(B) << endl;
return 0;
}