#include using namespace std; int inf = 1001001001; array mrg(array&a,array&b) { arrayar = {0,0,0,0}; ar[0] = max(a[0],a[2]+b[0]); ar[1] = max(b[1],b[2]+a[1]); ar[2] = a[2]+b[2]; ar[3] = max({a[3],b[3],a[1]+b[0]}); return ar; } struct SegmentTree { int n; vector> dat; SegmentTree() {} SegmentTree(int N) { n = 1; while(n < N) { n *= 2; } dat.resize(2*n-1); for(int i = n-1; i < 2*n-1; i++) { dat[i] = {1,1,1,1}; } for(int i = n-2; i >= 0; i--) { dat[i] = mrg(dat[i*2+1],dat[i*2+2]); } } void update(int x) { x += n-1; dat[x] = {0,0,-1,0}; while(x > 0) { x = (x-1)/2; dat[x] = mrg(dat[2*x+1],dat[2*x+2]); } } array query(int a, int b, int k, int l, int r) { if(r <= a || b <= l) return {0,0,0,0}; if(a <= l && r <= b) return dat[k]; array vl = query(a, b, 2*k+1, l, (l+r)/2); array vr = query(a, b, 2*k+2, (l+r)/2, r); return mrg(vl, vr); } array query(int a,int b) {//[a,b) return query(a,b,0,0,n); } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N,Q; cin >> N >> Q; vectorA(N); for(int i = 0; i < N; i++) { cin >> A[i]; } vectorL(Q),R(Q); for(int i = 0; i < Q; i++) { cin >> L[i] >> R[i]; L[i]--; R[i]--; } vectorl(Q,0),r(Q,inf); while(true) { vector>query; for(int i = 0; i < Q; i++) { if(l[i]+1 < r[i]) { int mid = (l[i]+r[i])/2; query.push_back({mid,1,i}); } } if(query.empty()) break; for(int i = 0; i < N; i++) { query.push_back({A[i],0,i}); } sort(query.begin(),query.end()); SegmentTree Seg(N); for(int i = 0; i < query.size(); i++) { if(query[i][1] == 0) { Seg.update(query[i][2]); } else { int id = query[i][2]; array now = Seg.query(L[id],R[id]+1); if(query[i][0] == 7) { cout << now[0] << " " << now[1] << " " << now[2] << " " << now[3] << endl; } if(-now[2]+max(0,now[3]-1) >= 1) { r[id] = query[i][0]; } else { l[id] = query[i][0]; } } } } for(int i = 0; i < Q; i++) { cout << r[i] << "\n"; } }