DSA problem
Sum of Subarray Ranges
Given an integer array nums, the range of a subarray is the difference between its largest and smallest element. Return the sum of the ranges of every contiguous subarray of nums.
The brute force enumerates all O(n²) subarrays and computes max and min on the fly while extending the right endpoint, giving O(n²) time and O(1) extra space. That is acceptable for the given constraint n <= 1000 and is sometimes the expected solution.
The follow-up asks for an O(n) solution, and the elegant approach uses the same contribution technique as "Sum of Subarray Minimums" applied twice. The sum of ranges equals the sum of subarray maxes minus the sum of subarray mins. For each index i, count the subarrays where it is the maximum (using "previous greater" and "next greater-or-equal") and the subarrays where it is the minimum (using "previous less" and "next less-or-equal"). Multiply by nums[i] and add or subtract appropriately.
Both subproblems use a monotonic stack and run in O(n). Because values can be negative, no modulus is required — just use 64-bit arithmetic to be safe.
Examples
nums = [1,2,3]4nums = [1,3,3]4nums = [4,-2,-3,4,1]59Constraints
- 1 <= nums.length <= 1000
- -10^9 <= nums[i] <= 10^9
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.