Given an integer array nums, consider every non empty contiguous subarray of nums. For each such subarray, define its range as the difference between its maximum element and its minimum element.
Return the sum of these ranges over all non empty contiguous subarrays of nums.
Note: A follow up asks whether you can solve this in O(n) time.
Constraints:
Input: nums = [5]-List[int]
Output: 0-int
Explanation: There is only one non-empty subarray, [5]. Its max and min are both 5, so its range is 5 - 5 = 0 and the sum is 0.
Input: nums = [2,2,2,2]-List[int]
Output: 0-int
Explanation: Every subarray consists only of 2s, so for each subarray, max = min = 2 and the range is 0. Summing all zeros gives 0.
Input: nums = [-1,4,-3,2]-List[int]
Output: 38-int
Explanation: Summing the range (max - min) over all non-empty contiguous subarrays: length 1 subarrays [-1], [4], [-3], [2] each give 0 (sum 0); length 2 subarrays [-1,4] (5), [4,-3] (7), [-3,2] (5) sum to 17; length 3 subarrays [-1,4,-3] (7), [4,-3,2] (7) sum to 14; and length 4 subarray [-1,4,-3,2] gives 7. The total is 0 + 17 + 14 + 7 = 38.
Input: nums = [1000000000,-1000000000,0,1000000000]-List[int]
Output: 10000000000-int
Explanation: Length 1 subarrays all have range 0 (sum 0); length 2 subarrays [1e9,-1e9] = 2e9, [-1e9,0] = 1e9, [0,1e9] = 1e9 sum to 4e9; length 3 subarrays [1e9,-1e9,0] = 2e9, [-1e9,0,1e9] = 2e9 sum to 4e9; and length 4 subarray [1e9,-1e9,0,1e9] = 2e9. The total is 0 + 4e9 + 4e9 + 2e9 = 1e10 = 10000000000.
Now, let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem: