Problem 516
Sum of Subarray Minimums
Medium · 20 pts · Array, Monotonic Stack
Problem
For every non-empty block of consecutive elements, take its minimum, and add all these minimums together. Print the total modulo 1000000007. Instead of looking at each block, count for each element how many blocks have it as their minimum: that is (positions you can extend to the left) × (positions you can extend to the right), found with a monotonic stack. Use a strict comparison on one side so that equal values are not counted twice. Keep the counts in a 64-bit integer type (long long in C++, long in Java) and take the remainder after every addition and multiplication: adding or multiplying two remainders can be larger than a 32-bit int can hold (Python needs nothing special).
Input
The first line contains an integer N, the size of the array. The second line contains N space-separated integers A[0], A[1], ..., A[N-1].
Output
Print the sum of all subarray minimums modulo 1000000007.
Constraints
1 <= N <= 30000; 1 <= A[i] <= 30000
Example input
4 3 1 2 4
Example output
17
Explanation
The blocks of 3 1 2 4 have minimums 3, 1, 2, 4 (single elements), 1, 1, 2 (pairs), 1, 1 (triples) and 1 (the whole array). Their sum is 3 + 1 + 2 + 4 + 1 + 1 + 2 + 1 + 1 + 1 = 17.