Sum of Subarray Minimums - Problem
Sum of Subarray Minimums
Imagine you have an array of integers, and you need to find every possible contiguous subarray within it. For each subarray, you find its minimum element, then sum all these minimums together.
For example, with array
• Subarrays of length 1:
• Subarrays of length 2:
• Subarrays of length 3:
• Subarrays of length 4:
Total sum: (3+1+2+4) + (1+1+2) + (1+1) + (1) = 17
Since the answer can be very large, return the result modulo 109 + 7.
Imagine you have an array of integers, and you need to find every possible contiguous subarray within it. For each subarray, you find its minimum element, then sum all these minimums together.
For example, with array
[3, 1, 2, 4]:• Subarrays of length 1:
[3], [1], [2], [4] → minimums: 3, 1, 2, 4• Subarrays of length 2:
[3,1], [1,2], [2,4] → minimums: 1, 1, 2• Subarrays of length 3:
[3,1,2], [1,2,4] → minimums: 1, 1• Subarrays of length 4:
[3,1,2,4] → minimum: 1Total sum: (3+1+2+4) + (1+1+2) + (1+1) + (1) = 17
Since the answer can be very large, return the result modulo 109 + 7.
Input & Output
example_1.py — Basic Array
$
Input:
[3,1,2,4]
›
Output:
17
💡 Note:
All subarrays: [3]→3, [1]→1, [2]→2, [4]→4, [3,1]→1, [1,2]→1, [2,4]→2, [3,1,2]→1, [1,2,4]→1, [3,1,2,4]→1. Sum = 3+1+2+4+1+1+2+1+1+1 = 17
example_2.py — Single Element
$
Input:
[11,81,94,43,3]
›
Output:
444
💡 Note:
For each element, calculate how many subarrays it's the minimum for. Element 3 is minimum in many subarrays, contributing significantly to the total sum.
example_3.py — Edge Case
$
Input:
[5]
›
Output:
5
💡 Note:
Single element array has only one subarray [5] with minimum 5, so the answer is 5.
Constraints
- 1 ≤ arr.length ≤ 3 × 104
- 1 ≤ arr[i] ≤ 3 × 104
- Return answer modulo 109 + 7
Visualization
Tap to expand
Understanding the Visualization
1
Identify Impact Zones
For each restaurant, find how far its influence extends left and right
2
Calculate Coverage
Each restaurant affects left_distance × right_distance segments as the minimum
3
Sum Total Impact
Multiply each restaurant's value by its coverage area
Key Takeaway
🎯 Key Insight: Calculate each element's contribution by finding how many subarrays it dominates, rather than generating all subarrays explicitly. Use monotonic stack to efficiently find the nearest smaller elements on both sides.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code