#2104
Sum of Subarray Ranges
MediumArrayStackMonotonic StackMonotonic StackArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a monotonic stack to efficiently calculate the contribution of each element as both a maximum and a minimum in all possible subarrays. This approach reduces the time complexity significantly.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a total sum variable to 0 and create two arrays to store the next and previous greater elements for each index.
- 2Step 2: Use a stack to find the next and previous greater elements for each element in the array.
- 3Step 3: For each element, calculate its contribution as a maximum and minimum based on its position in the subarrays.
- 4Step 4: Sum the contributions of all elements to get the final result.
solution.py22 lines
1def subArrayRanges(nums):
2 n = len(nums)
3 next_greater = [n] * n
4 prev_greater = [-1] * n
5 stack = []
6
7 for i in range(n):
8 while stack and nums[stack[-1]] < nums[i]:
9 next_greater[stack.pop()] = i
10 stack.append(i)
11
12 stack = []
13 for i in range(n - 1, -1, -1):
14 while stack and nums[stack[-1]] <= nums[i]:
15 prev_greater[stack.pop()] = i
16 stack.append(i)
17
18 total_sum = 0
19 for i in range(n):
20 total_sum += nums[i] * (next_greater[i] - i) * (i - prev_greater[i])
21
22 return total_sumℹ
Complexity note: This complexity is achieved because we traverse the array a constant number of times (once for finding next greater and once for previous greater), leading to linear time complexity.
- 1Each element contributes to multiple subarrays as both maximum and minimum.
- 2Using a monotonic stack helps efficiently find the next and previous greater elements.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.