Sum of Subarray Ranges

Given an integer array nums, return the sum of the differences between the maximum and minimum element of every subarray. For each subarray, range = max(subarray) - min(subarray). Example: Input: nums = [1,2,3] Output: 4 Explanation: The ranges are [0,1,2,0,1,0] across all subarrays, summing to 4. Pattern focus: Range Contribution with monotonic stacks.

Input Format

nums = array of integers

Output Format

sum of (maximum - minimum) over all subarrays

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

Examples

Example 1:

Input:

nums = [1,2,3]

Output:

4

Explanation:

The total range is obtained by adding each subarray's max-min difference.

Example 2:

Input:

nums = [1,3,3]

Output:

4

Explanation:

Equal values need careful boundary handling in contribution counts.

Loading...
Sum of Subarray Ranges - Monotonic Stack Queue