Problem 517
Sum of Subarray Ranges
Medium · 20 pts · Array, Monotonic Stack
Problem
The range of a block of consecutive elements is its largest element minus its smallest element. Add up the ranges of all non-empty blocks and print the total. With N up to 1000, a double loop that tracks the running maximum and minimum is fast enough; a monotonic stack gives O(N). The total can be far larger than 2^31, so store it in a 64-bit integer.
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 ranges.
Constraints
1 <= N <= 1000; -1000000000 <= A[i] <= 1000000000
Example input
3 1 2 3
Example output
4
Explanation
The blocks of 1 2 3 are [1], [2], [3] with range 0, [1 2] and [2 3] with range 1, and [1 2 3] with range 2. The total is 0 + 0 + 0 + 1 + 1 + 2 = 4.