给定 n n 和一个长度为 n n 的序列,求最长的最大值最小值相差不超过的序列
第一行两个有空格隔开的整数 k k , n n , k k 代表设定的最大值,代表序列的长度。第二行为 n n 个由空格隔开的整数 (1<=ai<=2000,000,000) ( 1 <= a i <= 2000 , 000 , 000 ) 表示序列。
看数据范围显然是个线性复杂度的题目,并不是比他大比他小的问题并不是单调栈。
于是想到了
two−pointer
t
w
o
−
p
o
i
n
t
e
r
记录指针扫到的区间中最大值和最小值检验合法性,然后把
R
R
<script id="MathJax-Element-1614" type="math/tex">R</script> 指针右移。 一旦不合法移动左指针 。我们现在解决的是最大最小值的问题,因为区间连续,所以可以单调队列维护。
#include<bits/stdc++.h>
using namespace std;
const int MAXN=3e6+5;
const int INF=2e9+7;
int a[MAXN],n,k;
struct mqueup{
deque<int>m,q;
inline void push(int x){
q.push_back(x);
while(m.size()&&x>m.back())m.pop_back();
m.push_back(x);
}
inline void pop(){
int v=q.front();q.pop_front();
if(v==m.front())m.pop_front();
}
inline int top(){
return m.front();
}
inline int size(){
return q.size();
}
}BIG;
struct mquedown{
deque<int>m,q;
inline void push(int x){
q.push_back(x);
while(m.size()&&x<m.back())m.pop_back();
m.push_back(x);
}
inline void pop(){
int v=q.front();q.pop_front();
if(v==m.front())m.pop_front();
}
inline int top(){
return m.front();
}
inline int size(){
return q.size();
}
}SMALL;
void PUSH(int x){
BIG.push(x);SMALL.push(x);
}
void POP(){
BIG.pop();SMALL.pop();
}
int querymax(){
return BIG.top();
}
int querymin(){
return SMALL.top();
}
bool check(){
if(!BIG.size())return 1;
if(querymax()-querymin()<=k)return 1;
return 0;
}
void moveleft(){
while(!check())POP();
}
int r=0,ans=0;
void moveright(){
++r;PUSH(a[r]);
moveleft();
}
int main(){
scanf("%d%d",&k,&n);
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
while(r<n){
moveright();
ans=max(ans,BIG.size());
}
cout<<ans<<endl;
return 0;
}