Problems > Sum of Every Range

Sum of Every Range

Difficulty: 2000 5000 ms 128 MB

math stack

The RANGE of a subarray is its maximum minus its minimum. Sum the ranges of all contiguous subarrays.

Input: the first line has N; the second line has N integers.

Output: the total of all subarray ranges.

Constraints:

  • 1 ≤ N ≤ 105
  • |ai| ≤ 109

Sample Tests

Input 1
3
1 3 2
Output 1
5
Input 2
2
5 5
Output 2
0

Read the Editorial

Discussion (opens after you solve — no spoilers before)

No comments yet.

Submit Your Solution

Log in or create a free account to run and submit code.