Total High-Low Spread of Every Subarray

Implement sumSubarrayRanges

Given an integer array arr, define a subarray's "spread" as its maximum value minus its minimum value. Find the sum of the spreads of every contiguous subarray. Since spread = max − min, the total sum splits cleanly in two: (sum of every subarray's maximum) minus (sum of every subarray's minimum). Each of those two sums is exactly the "sum of subarray minimums" problem — once directly, and once with every comparison flipped to find maximums instead. Each is solved by asking, per element, "in how many subarrays is this element the min (or max)?" — answered with a monotonic stack locating the nearest smaller (or greater) neighbor on each side in a single linear pass. Four linear passes total replace the brute force's quadratic enumeration of every subarray.

Example 1:

Input: arr = [5,2,6,1]

Output: 26

Example 2:

Input: arr = [7,3,8,2,5]

Output: 53

Example 3:

Input: arr = [3,7,2,9,4]

Output: 61

+ 3 hidden test cases run on Submit.

Constraints:

  • 1 ≤ arr.length ≤ 12
  • 1 ≤ arr[i] ≤ 100
  • The answer fits comfortably in a 32-bit signed integer for this input size

arr =

[5, 2, 6, 1]