Under construction

Still being built. Things may change

Dinosaur Bones Digging

Time limit5sMemory limit2048 MB

Summary
For each plan [l, r], the task is to pick a main sector m that maximizes a_m times the number of sectors in [l, r] deeper than a_m.
Level

Hard9 of 10

Topics
Segment tree, Sorting, Array
Solved
No attempts yet

Problem

Paleontologists are looking for dinosaur bones! They have already found a long line of nn square sectors, numbered from 1 to nn. Each square has a side of 1 meter. Preliminary measurements showed that in sector ii, the depth of soil potentially containing dinosaur bones is aia_i meters. Below that depth lies solid bedrock. All the numbers aia_i are distinct integers.

Scientists have prepared qq research plans. Each plan builds a research station on the subsegment of sectors from ℓj\ell_j to rjr_j. After picking the subsegment, they pick one of its sectors mm (ℓj≤m≤rj\ell_j \le m \le r_j) as the main sector.

A special device is buried in the main sector at a depth of ama_m meters. The device analyzes the top ama_m meters of every sector under the station whose depth is strictly greater than ama_m. In total, am⋅ka_m \cdot k cubic meters of soil are analyzed, where kk is the number of sectors under the station (between ℓj\ell_j and rjr_j, inclusive) that are deeper than the main sector.

The paleontologists want to analyze as much soil as possible. Find the maximum volume of soil that can be analyzed when one plan is chosen and its main sector is then chosen optimally.

Input

The first line contains a single integer nn, the number of sectors (1≤n≤1061 \le n \le 10^6).

The second line contains nn distinct integers a1,a2,…,ana_1, a_2, \ldots, a_n, the depths of the sectors (1≤ai≤1091 \le a_i \le 10^9).

The next line contains a single integer qq, the number of plans (1≤q≤1061 \le q \le 10^6).

Each of the next qq lines contains two integers ℓj\ell_j and rjr_j, the endpoints of the subsegment for the jj-th plan (1≤ℓj≤rj≤n1 \le \ell_j \le r_j \le n).

Output

Print a single integer on one line: the maximum volume of analyzed soil in cubic meters.

Hint

In the example, the scientists should pick the first plan and the first sector as its main sector. Then 3⋅3=93 \cdot 3 = 9 cubic meters of soil are analyzed, since 55, 77, and 44 are deeper than 33.

Examples1

  1. Example 1

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