problems / 112

Sum of Subarray Minimums

medium monotonic-stack stack arrays 1000 ms · 256 MB

Sum of Subarray Minimums

You are given an array a of n integers. A contiguous subarray is a non-empty run of consecutive elements a[i], a[i+1], ..., a[j] for some 1 ≤ i ≤ j ≤ n.

For every contiguous subarray, take its minimum element. Sum those minimums over all n·(n+1)/2 contiguous subarrays, and report the sum modulo 10^9 + 7.

Input

The first line contains a single integer n (1 ≤ n ≤ 3·10^5).

The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9).

Output

Print a single integer: the sum of the minimums of all contiguous subarrays of a, modulo 10^9 + 7.

Notes

In the first example, the array is [3, 1, 2, 4]. Its subarrays and minimums are:

  • [3] → 3, [1] → 1, [2] → 2, [4] → 4
  • [3,1] → 1, [1,2] → 1, [2,4] → 2
  • [3,1,2] → 1, [1,2,4] → 1
  • [3,1,2,4] → 1

The total is 3+1+2+4+1+1+2+1+1+1 = 17.

When several subarrays share the same minimum value, be careful not to double-count or miss any of them — the second example uses repeated values to probe exactly that.

Example 1

Input

4
3 1 2 4

Output

17

Example 2

Input

5
1 3 1 2 1

Output

18

Hints · reveal one at a time if you're stuck

Hint 1

Summing over all subarrays directly is far too slow. Flip the sum around: for each position, ask how many subarrays have it as their minimum, then add its value times that count.

Hint 2

For a position, the subarrays where it is the minimum extend left until a strictly smaller value and right until a smaller-or-equal value. Find these boundaries in linear time with a monotonic stack, and use the strict test on one side and the non-strict test on the other so equal values are not double counted.

report an issue Prefer your own editor? sooks prep 112 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.