Sum of Subarray Ranges

medium

The range of a subarray is its maximum minus its minimum. Given an array nums, return the sum of the ranges over all contiguous subarrays.

Hints

A subarray's range is max - min, so the total splits into sum of maxes minus sum of mins.
Each sum is the contribution trick from Sum of Subarray Minimums, mirrored for maximums.
Two monotonic-stack passes per sum; subtract the two totals.

Common doubts

Summation is linear: the sum of (max - min) over subarrays equals the sum of maxes minus the sum of mins, and each can be counted separately.
Just flip the comparisons: previous strictly-greater and next greater-or-equal for max, versus previous strictly-smaller and next smaller-or-equal for min.
No, but the total exceeds 32 bits, so accumulate in a 64-bit integer.

Interview follow-ups

Yes — the exact answer fits in signed 64-bit; just ensure every intermediate product uses 64-bit arithmetic.
Add the two contribution sums instead of subtracting them.

Fun facts

  • Decomposing an aggregate into independent per-element contributions is one of the most reusable competitive-programming moves.
  • This problem is literally 'Sum of Subarray Minimums' run twice with the comparisons flipped.

Asked at

AmazonGoogle
Frequently Sometimes Occasionally
Example 1
Input: nums = [1,2,3]
Output: 4
Subarray ranges are 0,1,2,0,1,0; their sum is 4.
Example 2
Input: nums = [1,3,3]
Output: 4
Ranges: 0,2,2,0,0,0 -> 4.
Constraints

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

Solve this problem →