#include <iostream>
#include<stdio.h>
using namespace std;
const int maxn=50000+5;
int n,q;
int height[maxn];
struct segtree
{
int left,right;
int maxx,minn;
};
segtree tree[maxn*4];
#include<stdio.h>
using namespace std;
const int maxn=50000+5;
int n,q;
int height[maxn];
struct segtree
{
int left,right;
int maxx,minn;
};
segtree tree[maxn*4];
void build(int low,int high,int index)
{
tree[index].left=low;
tree[index].right=high;
if(low==high)
{
tree[index].maxx=height[low];
tree[index].minn=height[low];
return;
}
else
{
int mid=(low+high)/2;
build(low,mid,index*2);
build(mid+1,high,index*2+1);
tree[index].maxx=max(tree[index*2].maxx,tree[index*2+1].maxx);
tree[index].minn=min(tree[index*2].minn,tree[index*2+1].minn);
}
}
{
tree[index].left=low;
tree[index].right=high;
if(low==high)
{
tree[index].maxx=height[low];
tree[index].minn=height[low];
return;
}
else
{
int mid=(low+high)/2;
build(low,mid,index*2);
build(mid+1,high,index*2+1);
tree[index].maxx=max(tree[index*2].maxx,tree[index*2+1].maxx);
tree[index].minn=min(tree[index*2].minn,tree[index*2+1].minn);
}
}
int qmax(int low,int high,int index)
{
if(tree[index].left==low&&tree[index].right==high)
{
return tree[index].maxx;
}
else
{
int mid=(tree[index].left+tree[index].right)/2;
if(high<=mid)
{
return qmax(low,high,index*2);
}
else if(low>mid)
{
return qmax(low,high,index*2+1);
}
else
{
return max(qmax(low,mid,index*2),qmax(mid+1,high,index*2+1));
}
}
}
{
if(tree[index].left==low&&tree[index].right==high)
{
return tree[index].maxx;
}
else
{
int mid=(tree[index].left+tree[index].right)/2;
if(high<=mid)
{
return qmax(low,high,index*2);
}
else if(low>mid)
{
return qmax(low,high,index*2+1);
}
else
{
return max(qmax(low,mid,index*2),qmax(mid+1,high,index*2+1));
}
}
}
int qmin(int low,int high,int index)
{
if(tree[index].left==low&&tree[index].right==high)
{
return tree[index].minn;
}
else
{
int mid=(tree[index].left+tree[index].right)/2;
if(high<=mid)
{
return qmin(low,high,index*2);
}
else if(low>mid)
{
return qmin(low,high,index*2+1);
}
else
{
return min(qmin(low,mid,index*2),qmin(mid+1,high,index*2+1));
}
}
}
{
if(tree[index].left==low&&tree[index].right==high)
{
return tree[index].minn;
}
else
{
int mid=(tree[index].left+tree[index].right)/2;
if(high<=mid)
{
return qmin(low,high,index*2);
}
else if(low>mid)
{
return qmin(low,high,index*2+1);
}
else
{
return min(qmin(low,mid,index*2),qmin(mid+1,high,index*2+1));
}
}
}
int main()
{
scanf("%d%d",&n,&q);
for(int i=1;i<=n;i++)
scanf("%d",&height[i]);
build(1,n,1);
while(q--)
{
int a,b;
scanf("%d%d",&a,&b);
printf("%d\n",qmax(a,b,1)-qmin(a,b,1));
}
return 0;
}
{
scanf("%d%d",&n,&q);
for(int i=1;i<=n;i++)
scanf("%d",&height[i]);
build(1,n,1);
while(q--)
{
int a,b;
scanf("%d%d",&a,&b);
printf("%d\n",qmax(a,b,1)-qmin(a,b,1));
}
return 0;
}