板子*3
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #define int long long using namespace std; int n,q,h[500050],dp1[500050][65],dp2[500050][65]; void init() { for(int i=1;i<=n;i++)dp1[i][0]=h[i]; for(int j=1;(1<<j)<=n;j++) for(int i=1;i+(1<<j)-1<=n;i++) dp1[i][j]=max(dp1[i][j-1],dp1[i+(1<<j-1)][j-1]); for(int i=1;i<=n;i++)dp2[i][0]=h[i]; for(int j=1;(1<<j)<=n;j++) for(int i=1;i+(1<<j)-1<=n;i++) dp2[i][j]=min(dp2[i][j-1],dp2[i+(1<<j-1)][j-1]); } int maxnum(int l,int r) { int k=log2(r-l+1); return max(dp1[l][k],dp1[r-(1<<k)+1][k]); } int minnum(int l,int r) { int k=log2(r-l+1); return min(dp2[l][k],dp2[r-(1<<k)+1][k]); } signed main() { scanf("%lld%lld",&n,&q); for(int i=1;i<=n;i++)scanf("%lld",&h[i]); init(); int x,y; for(int i=1;i<=q;i++) { scanf("%lld%lld",&x,&y); printf("%lld ",maxnum(x,y)-minnum(x,y)); } return 0; }