This page is still under construction.

Parts of this page are still being built. What you see may change.

Balanced Lineup

Time limit1sMemory limit128 MB

Summary
Given a static array of cow heights, answer queries giving the max minus min over each range [A, B].
Level

Medium5 of 10

Topics
Segment tree, Array
Solved
No attempts yet

Problem

For the daily milking, Farmer John's NN cows (1≤N≤50,0001 \le N \le 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 takes 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 QQ (1≤Q≤200,0001 \le Q \le 200{,}000) potential groups of cows and their heights (1≤height≤1,000,0001 \le \text{height} \le 1{,}000{,}000). For each group, help him determine the difference in height between the shortest and the tallest cow in the group.

Input

  • Line 1: Two space-separated integers, NN and QQ.
  • Lines 2 to N+1N+1: Line i+1i+1 contains a single integer, the height of cow ii.
  • Lines N+2N+2 to N+Q+1N+Q+1: Two integers AA and BB (1≤A≤B≤N1 \le A \le B \le N), representing the range of cows from AA to BB inclusive.

Output

  • Lines 1 to QQ: Each line contains a single integer, the difference in height between the tallest and the shortest cow in the corresponding range.

Examples1

  1. Example 1

    Input
    6 3
    1
    7
    3
    4
    2
    5
    1 5
    4 6
    2 2
    
    Expected output
    6
    3
    0