Stacks and Queues Monotonic stack
217. Sum of Subarray Ranges
You are given an array of integers nums. The range of a subarray is its largest element minus its
smallest element. Return the sum of the ranges of all the subarrays of nums.
A subarray is a contiguous run of one or more elements. Two subarrays are different if they start or end at different positions, even when they hold the same values. A subarray of one element has range 0.
Example 1
Input: nums = [3, 1, 4, 2]
16Explanation: The four single elements have range 0. The pairs [3,1], [1,4] and [4,2] have ranges 2, 3 and 2.
[3,1,4], [1,4,2] and the whole array each have range 4 − 1 = 3. The total is 7 + 9 = 16.
Example 2
Input: nums = [2, 2, 2]
0Explanation: Every subarray holds only 2s, so its largest and smallest elements are equal and its range is 0.
Example 3
Input: nums = [-500000000, 500000000, -500000000]
3000000000Explanation: The three subarrays longer than one element each hold both values, so each has range 5 × 108 − (−5 × 108) = 109.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 105-5 × 108 ≤ nums[i] ≤ 5 × 108
Clarifying questions
What you would ask an interviewer before writing any code.