B. Approximating a Constant Range
When Xellos is doing a practice course in university, he once had to measure the intensity of a effect that slowly appro ached equilibrium. A good the determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points That seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging-but why not make a similar programming contest problem While the we ' re at it?
You ' re given a sequence of n data points a n . There aren ' t any big jumps between consecutive data points -for each 1≤ I < n , it ' s guaranteed that | A i + 1 - a i | ≤1.
A range [l, R] of data points is said to being almost constant if the difference between the larges T and the smallest value in that range are at most 1. Formally, let m is the maximum and m the minimum value of ai for l ≤ i ≤ r; the range [l, R] is almost constant if m - M ≤1.
Find the length of the longest almost constant range.
Input
The first line of the input contains a single integer n (2≤ n ≤100)-the number of data p Oints.
The second line contains n integers a1, a2, ..., a n (1≤ ai ≤100).
Output
Print a single number-the maximum length of a almost constant range of the given sequence.
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
Note
In the first sample, the longest almost constant range are [2, 5]; its length (the number of data points in it) is 4.
In the second sample, there is three almost constant ranges of length 4: [1, 4], [6, 9] and [7, ten]; the Only almost constant range of the maximum length 5 is [6].
1#include <cstdio>2#include <vector>3#include <cmath>4#include <queue>5#include <map>6#include <cstring>7#include <algorithm>8 using namespacestd;9typedefLong Longll;Tentypedef unsignedLong Longull; One Const intmaxn=100005; A intMain () - { - intN; the intA[MAXN],S[MAXN]; -scanf"%d",&n); - for(intI=1; i<=n;i++) -scanf"%d",&a[i]); + intans=1; - for(intI=1, l=1, r=0; i<=n;i++) + { A while(L<=r&&a[i]<a[s[r]]) r--; ats[++r]=i; - while(a[s[r]]>a[s[l]]+1) l++; -Ans=max (ans,s[r]-s[l]+1); - } - for(intI=1, l=1, r=0; i<=n;i++) - { in while(L<=r&&a[i]>a[s[r]]) r--; -s[++r]=i; to while(a[s[l]]>a[s[r]]+1) l++; +Ans=max (ans,s[r]-s[l]+1); - } theprintf"%d\n", ans); * return 0; $}
Codeforces 602B approximating a Constant Range