907.Sum of Subarray Minimums
===
###### tags: `Medium`,`Array`,`DP`,`Stack`
[907. Sum of Subarray Minimums](https://leetcode.com/problems/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** $10^9 + 7$ .
### 範例
```
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.
```
```
Input: arr = [11,81,94,43,3]
Output: 444
```
**Constraints**:
* `1 <= arr.length` <= $3 * 10^4$
* `1 <= arr[i]` <= $3 * 10^4$
### 解答
#### Python
```python=
class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
arr = [0] + arr
stack = [0]
dp = [0] * len(arr)
for i, n in enumerate(arr):
while arr[stack[-1]] > n:
stack.pop()
j = stack[-1]
dp[i] = dp[j] + (i-j) * n
stack.append(i)
return sum(dp) % 1000000007
```
> [name=Yen-Chi Chen][time=Fri, Nov 25, 2022 10:40 PM]
```python=
class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
res = 0
stack = []
arr = [0] + arr + [0]
for idx, num in enumerate(arr):
while stack and arr[stack[-1]] > num:
cur = stack.pop()
res += arr[cur] * (idx-cur) * (cur-stack[-1])
stack.append(idx)
return res% (10**9+7)
```
>[name=Dan][time=Sat, Jan 20, 2024 08:03 PM]
#### C++
```cpp=
class Solution {
public:
int sumSubarrayMins(vector<int>& arr) {
stack<int> s;
vector<int> dp(arr.size());
for (int i = 0; i < arr.size(); i++) {
int n = arr[i];
while(!s.empty() && arr[s.top()] >= n) {
s.pop();
}
if (s.empty()) {
dp[i] = (i + 1) * n;
} else {
int j = s.top();
dp[i] = dp[j] + (i - j) * n;
}
s.push(i);
}
int result = 0;
for (auto t : dp) {
result = (result + t) % 1000000007;
}
return result;
}
};
```
Time: $O(n)$
Extra Space: $O(n)$
> [name=Yen-Chi Chen][time=Fri, Nov 25, 2022 10:40 PM]
### Reference
[回到題目列表](https://hackmd.io/@Marsgoat/leetcode_every_day)