Skip to content

Commit

Permalink
907
Browse files Browse the repository at this point in the history
  • Loading branch information
ProHiryu committed Aug 5, 2020
1 parent 47702f7 commit 05dfaee
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions Stack/907.md
@@ -0,0 +1,34 @@
## [907] Sum of Subarray Minimums

#### Description

[link](https://leetcode.com/problems/sum-of-subarray-minimums/)

---

#### Solution

- See Code

---

#### Code

> O(n)
```python
class Solution:
def sumSubarrayMins(self, A: List[int]) -> int:
# The times a number n occurs in the minimums is |left_bounday-indexof(n)| * |right_bounday-indexof(n)|
# The total sum is sum([n * |left_bounday - indexof(n)| * |right_bounday - indexof(n)| for n in array]
res = 0
stack = [] # non-decreasing
A = [float('-inf')] + A + [float('-inf')]
for i, n in enumerate(A):
# stack[-1], i is the left and right bounday
while stack and A[stack[-1]] > n:
cur = stack.pop()
res += A[cur] * (i - cur) * (cur - stack[-1])
stack.append(i)
return res % (10**9 + 7)
```

0 comments on commit 05dfaee

Please sign in to comment.