You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray.
Return the sum of all subarray ranges of nums.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,2,3] Output: 4 Explanation: The 6 subarrays of nums are the following: [1], range = largest - smallest = 1 - 1 = 0 [2], range = 2 - 2 = 0 [3], range = 3 - 3 = 0 [1,2], range = 2 - 1 = 1 [2,3], range = 3 - 2 = 1 [1,2,3], range = 3 - 1 = 2 So the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4.
Example 2:
Input: nums = [1,3,3] Output: 4 Explanation: The 6 subarrays of nums are the following: [1], range = largest - smallest = 1 - 1 = 0 [3], range = 3 - 3 = 0 [3], range = 3 - 3 = 0 [1,3], range = 3 - 1 = 2 [3,3], range = 3 - 3 = 0 [1,3,3], range = 3 - 1 = 2 So the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4.
Example 3:
Input: nums = [4,-2,-3,4,1] Output: 59 Explanation: The sum of all subarray ranges of nums is 59.
Constraints:
1 <= nums.length <= 1000-109 <= nums[i] <= 109
Follow-up: Could you find a solution with O(n) time complexity?
Problem Overview: You are given an integer array and must compute the sum of ranges for all subarrays. The range of a subarray equals max(subarray) - min(subarray). The task is to efficiently aggregate this value across every possible subarray.
Approach 1: Brute Force Expansion (O(n²) time, O(1) space)
Start a subarray at each index and expand it to the right. While expanding, maintain the current minimum and maximum values. Each time the window grows, update min and max, then add max - min to the result. This avoids recomputing min and max from scratch but still requires checking every subarray pair (i, j). The algorithm runs in O(n²) time with constant extra space. This approach is straightforward and useful for validating logic, but it becomes slow for large arrays because the number of subarrays grows quadratically.
Approach 2: Monotonic Stack Contribution Method (O(n) time, O(n) space)
The key observation is that each element contributes to multiple subarrays as both a maximum and a minimum. Instead of enumerating subarrays, count how many subarrays treat a value as their maximum and how many treat it as their minimum. The difference between these contributions determines its impact on the final sum.
Use monotonic stacks to find the previous and next greater elements for maximum contribution and the previous and next smaller elements for minimum contribution. For an index i, the number of subarrays where nums[i] is the maximum equals (i - prevGreater) * (nextGreater - i). Apply a similar calculation using smaller elements to count when it acts as the minimum. Multiply each count by the element value and accumulate the difference.
This transforms the problem into two linear scans using stack operations such as push, pop, and index tracking. Each element enters and leaves the stack once, producing O(n) time complexity and O(n) auxiliary space. The technique is widely used in problems involving subarray contributions and boundary discovery in stack-based algorithms on an array.
Recommended for interviews: Interviewers expect the monotonic stack solution because it demonstrates understanding of contribution counting and boundary discovery. Implementing the brute force approach first shows problem comprehension, but the O(n) stack solution shows strong algorithmic intuition and familiarity with advanced array techniques.
The Brute Force Approach involves iterating over all possible subarrays of the given array. For each subarray, find the maximum and minimum elements, and calculate the difference. Sum all these differences to get the final answer. While this approach is simple, it is not efficient for larger arrays due to its quadratic time complexity.
This approach iterates over the array, using two nested loops where the outer loop sets the starting point of the subarray and the inner loop extends the subarray to all subsequent points. It calculates both the maximum and minimum for each subarray, computing their difference, which is accumulated into the total sum.
Time Complexity: O(n^2), where n is the length of the array, due to the nested loop structure.
Space Complexity: O(1), no extra data structures are used apart from loop variables.
The Monotonic Stack Approach optimizes the calculation by focusing on the contribution of each element as a maximum or minimum in various subarrays. By using two stacks, the solution efficiently determines the range extend of each number within the subarray, deriving the number of subarrays it could be the maximum or minimum of. This optimized approach emphasizes reducing redundant calculations commonly inherent in brute force methods.
This C solution centers upon leveraging two stacks for determining the role of each element both as a minimum and maximum across potential subarrays, to accumulate the distinct contribution of each element to the total subarray range.
Time Complexity: O(n), regarded as linear due to the stack operations limiting the number of necessary operations to a reduced count.
Space Complexity: O(n), for storing the elements in the stack structures.
| Approach | Complexity |
|---|---|
| Brute Force Approach | Time Complexity: O(n^2), where n is the length of the array, due to the nested loop structure. |
| Monotonic Stack Approach | Time Complexity: O(n), regarded as linear due to the stack operations limiting the number of necessary operations to a reduced count. |
| Default Approach | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Expansion | O(n²) | O(1) | Useful for understanding the problem or verifying correctness on small arrays |
| Monotonic Stack Contribution | O(n) | O(n) | Best choice for large inputs and expected solution in coding interviews |
L10. Sum of subarray ranges | Stack and Queue Playlist • take U forward • 141,575 views views
Watch 9 more video solutions →Practice Sum of Subarray Ranges with our built-in code editor and test cases.
Practice on FleetCode