Magical Subarrays

Each query asks for the longest subarray inside [L,R] with every element between its first and last values.

Hard9Divide and conquerSegment treeStackNo attempts yetTime limit4sMemory limit128 MB

Problem

Luka walks into the house of the witch Marica, and she starts questioning him about her array AA of NN numbers. Each question is a pair of integers LL and RR that marks the subarray running from ALA_L to ARA_R.

For every question Luka has to answer with the length of the longest magical subarray contained in that subarray. The whole queried subarray is allowed.

A subarray is magical when every value in it lies between its first value and its last value. That is, Al,Al+1,,ArA_l, A_{l+1}, \dots, A_r is magical when min(Al,Ar)Akmax(Al,Ar)\min(A_l, A_r) \le A_k \le \max(A_l, A_r) holds for every kk with lkrl \le k \le r.

For example, [1,3,1,2,4][1, 3, 1, 2, 4] and [4,1,1,2,1][4, 1, 1, 2, 1] are magical, while [3,3,4,1][3, 3, 4, 1] is not. A subarray of length 1 is always magical, so every answer is at least 1.

Input

The first line contains the length of the array NN. (1N5000001 \le N \le 500\,000)

The second line contains the elements A1,A2,,ANA_1, A_2, \dots, A_N, separated by spaces. (1Ai1091 \le A_i \le 10^9)

The third line contains the number of questions QQ. (1Q5000001 \le Q \le 500\,000)

Each of the next QQ lines contains two integers LL and RR, in that order. (1LRN1 \le L \le R \le N)

Output

Print the answer to the iith question on the iith line, as a single integer.