题目描述
有n个数,要在这n个中选择连续的m个数,使得这m个数中最大值与最小值不之差不超过k,求最大的m。
输入文件
第一行包含个两个整数k,n;
第二行n个整数(int以内)
输出文件
一个整数m
样例输入
2 6
1 15 15 15 15 1
样例输出
4
限制与约定
对于30%的数据,n<=10000
对于50%的数据,n<=100000
对于70%的数据,n<=1000000
对于100%的数据,n<=3000000,k<=1000000000
时间限制:1s
空间限制:128MB
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<cmath> using namespace std; const int maxn = 3000000 + 10 ; int Max[maxn],Min[maxn],ans,a[maxn]; struct FastIO { static const int S = 1e7; int wpos; char wbuf[S]; FastIO() : wpos(0) {} inline int xchar() { static char buf[S]; static int len = 0, pos = 0; if (pos == len) pos = 0, len = fread(buf, 1, S, stdin); if (pos == len) exit(0); return buf[pos++]; } inline int xuint() { int c = xchar(), x = 0; while (c <= 32) c = xchar(); for (; '0' <= c && c <= '9'; c = xchar()) x = x * 10 + c - '0'; return x; } inline int xint() { int s = 1, c = xchar(), x = 0; while (c <= 32) c = xchar(); if (c == '-') s = -1, c = xchar(); for (; '0' <= c && c <= '9'; c = xchar()) x = x * 10 + c - '0'; return x * s; } inline void xstring(char *s) { int c = xchar(); while (c <= 32) c = xchar(); for (; c > 32; c = xchar()) * s++ = c; *s = 0; } inline void wchar(int x) { if (wpos == S) fwrite(wbuf, 1, S, stdout), wpos = 0; wbuf[wpos++] = x; } /* inline void wint(ll x) { if (x < 0) wchar('-'), x = -x; char s[24]; int n = 0; while (x || !n) s[n++] = '0' + x % 10, x /= 10; while (n--) wchar(s[n]); wchar('\n'); } inline void wstring(const char *s) { while (*s) wchar(*s++); }*/ ~FastIO() { if (wpos) fwrite(wbuf, 1, wpos, stdout), wpos = 0; } } io; inline int read(){ char ch = getchar(); int x = 0, f = 1; while(ch < '0' || ch > '9'){ if(ch == '-') f = -1; ch = getchar(); } while('0' <= ch && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } int main() { int k,n,c=1; //cin>>k>>n; k = io.xuint(); n = io.xuint(); for(int i=1;i<=n;i++) a[i]=io.xuint(); int minl=1,minr=0,maxl=1,maxr=0; for(int i=1;i<=n;i++) { while(maxr>=maxl && a[Max[maxr]] > a[i]) maxr--; while(minr>=minl && a[Min[minr]] < a[i]) minr--; Max[++maxr]=i; Min[++minr]=i; while( a[Min[minl]] - a[Max[maxl]] > k ) if( Max[maxl] > Min[minl]) c=Min[minl]+1,minl++; else c=Max[maxl]+1,maxl++; ans=max(ans,i-c+1); } cout<<ans; return 0; }