//题意:给定Q组牛的身高然后计算最高的和最低的身高差
//思路:明显是线段树维护每个区间之间最高的身高和最低的身高
#include <iostream>
#include <vector>
using namespace std;
#define INF 1<<15
//每个结点维护的数据是当前区间的最高身高和最低身高
vector<int>Tallest;
vector<int>Shortest;
static int N,Q;
void initHeight(int n){
N = 1;
while(N<n)N*=2;//好计算
Tallest.resize(2*N+1);
Shortest.resize(2*N+1);
for (int i=0;i<N*2+1;++i){
fill(Shortest.begin(),Shortest.end(),INF);
fill(Tallest.begin(),Tallest.end(),0);
}
}
void updateHeight(int h,int k){
//叶子结点
k+=N-1;
Tallest[k] = max(Tallest[k],h);
Shortest[k] = min(Shortest[k],h);
while(k>0){
k = (k-1)/2;
Tallest[k] = max(Tallest[k*2+1],Tallest[k*2+2]);
Shortest[k] = min(Shortest[k*2+1],Shortest[k*2+2]);
}
}
//下面是查找区间内的最高值
int queryTallest(int a,int b,int k,int l,int r){
if (r<=a||b<=l)
return 0;
//如果完全包含的话返回当前结点的值
if (a<=l&&r<=b)
{
return Tallest[k];
}
else{
int h1 = queryTallest(a,b,k*2+1,l,(l+r)/2);
int h2 = queryTallest(a,b,k*2+2,(l+r)/2,r);
return max(h1,h2);
}
}
//查找最小值
int queryShortest(int a,int b,int k,int l,int r){
if (r<=a||b<=l)
return INF;
//如果完全包含的话返回当前结点的值
if (a<=l&&r<=b)
{
return Shortest[k];
}
else{
int h1 = queryShortest(a,b,k*2+1,l,(l+r)/2);
int h2 = queryShortest(a,b,k*2+2,(l+r)/2,r);
return min(h1,h2);
}
}
int main(){
int n;
scanf("%d %d",&n,&Q);
initHeight(n);
for (int i=0;i<n;++i)
{
int h;
scanf("%d",&h);
updateHeight(h,i);//第i个值更新
}
int l,r;
for(int j=0;j<Q;++j){
scanf("%d %d",&l,&r);
int h1 = queryTallest(l-1,r,0,0,N);
int s1 = queryShortest(l-1,r,0,0,N);
printf("%d\n",h1-s1);
}
return 0;
}