Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
34 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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) | ||
``` |