---
description: https://leetcode.com/problems/sum-of-subarray-minimums/
---

# 907. Sum of Subarray Minimums

Given an array of integers arr, find the sum of `min(b)`, where `b` ranges over every (contiguous) subarray of `arr`. Since the answer may be large, return the answer **modulo** `109 + 7`.

&#x20;

**Example 1:**

```
Input: arr = [3,1,2,4]
Output: 17
Explanation: 
Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. 
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.
Sum is 17.
```

**Example 2:**

```
Input: arr = [11,81,94,43,3]
Output: 444
```

&#x20;

**Constraints:**

* `1 <= arr.length <= 3 * 104`
* `1 <= arr[i] <= 3 * 104`

问数组的所有子数组内最小值的和。sum(arr(i) \* cnt(i)), cnt(i) 是以arr\[i]为最小值的子数组个数。设\[l, i, r]是以arr\[i]为最小值的最长子数组，那cnt\[i]即（左边选个长度 \* 右边选个长度）的所有可能性: (i - l) \* (r - i). 为了对每个arr\[i]找到对应的l和r，用monotonic stack存当前最小值所在index，当arr\[i]比s\[-1]还小时，抛出s\[-1]且res += (i - s\[-1]) \* (s\[-1] \* s\[-2]), 在s.append(i)。

```python
class Solution:
    def sumSubarrayMins(self, arr: List[int]) -> int:
        arr = [0] + arr + [0]
        s, res = [], 0
        for i, num in enumerate(arr):
            while s and num < arr[s[-1]]:
                j = s.pop()
                res = (res + (i - j) * (j - s[-1]) * arr[j]) % (10 ** 9 + 7)
            s.append(i)
        return res 
    
```
