# G - Balanced Lineup

For the daily milking, Farmer John's N cows (1 ≤ N ≤ 50,000) always line up in the same order. One day Farmer John decides to organize a game of Ultimate Frisbee with some of the cows. To keep things simple, he will take a contiguous range of cows from the milking lineup to play the game. However, for all the cows to have fun they should not differ too much in height.

Farmer John has made a list of Q (1 ≤ Q ≤ 200,000) potential groups of cows and their heights (1 ≤ height ≤ 1,000,000). For each group, he wants your help to determine the difference in height between the shortest and the tallest cow in the group.

Input
Line 1: Two space-separated integers, N and Q.
Lines 2.. N+1: Line i+1 contains a single integer that is the height of cow i
Lines N+2.. N+ Q+1: Two integers A and B (1 ≤ A ≤ B ≤ N), representing the range of cows from A to B inclusive.

Output
Lines 1.. Q: Each line contains a single integer that is a response to a reply and indicates the difference in height between the tallest and shortest cow in the range.

Sample Input
6 3
1
7
3
4
2
5
1 5
4 6
2 2

Sample Output
6
3
0

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cctype>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <stack>
#include <queue>

using namespace std;
#define lson left,mid,root << 1
#define rson mid+1,right,root << 1 | 1
typedef long long ll;

const int maxn = 1e6 + 10;

ll sum1[maxn << 2];
ll sum2[maxn << 2];
ll a[maxn];

int n,q;

void pushup(ll root)
{
sum1[root] = max(sum1[root << 1] , sum1[root << 1 | 1]);
sum2[root] = min(sum2[root << 1] , sum2[root << 1 | 1]);
}

void build(ll left, ll right, ll root)
{
if(left == right)
{
sum1[root] = a[left];
sum2[root] = a[left];
return ;
}
ll mid = left + right >> 1 ;
build(lson);
build(rson);
pushup(root);
}

ll querymax(ll left, ll right, ll root, ll L, ll R)
{
if(L <= left && right <= R)
return sum1[root];
ll mid = left + right >> 1;
ll ans = 0;
if(L <= mid)
ans = max(ans, querymax(lson, L, R));
if(R > mid)
ans = max(ans, querymax(rson, L, R));
return ans;

}

ll querymin(ll left, ll right, ll root, ll L, ll R)
{
if(L <= left && right <= R)
return sum2[root];
ll mid = left + right >> 1;
ll ans = 0x3f3f3f;
if(L <= mid)
ans = min(ans, querymin(lson, L, R));
if(R > mid)
ans = min(ans, querymin(rson, L, R));
return ans;
}

int main()
{
scanf("%d%d",&n,&q);
for(int i = 1; i <= n; i ++)
scanf("%lld",&a[i]);
build(1,n,1);
while(q --)
{
ll l,r;
scanf("%lld%lld",&l,&r);
ll maxx = querymax(1,n,1,l,r);
ll minx = querymin(1,n,1,l,r);
printf("%lld\n",maxx - minx);
}
return 0;
}