File tree 1 file changed +34
-0
lines changed
1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ ## [ 907] Sum of Subarray Minimums
2
+
3
+ #### Description
4
+
5
+ [ link] ( https://leetcode.com/problems/sum-of-subarray-minimums/ )
6
+
7
+ ---
8
+
9
+ #### Solution
10
+
11
+ - See Code
12
+
13
+ ---
14
+
15
+ #### Code
16
+
17
+ > O(n)
18
+
19
+ ``` python
20
+ class Solution :
21
+ def sumSubarrayMins (self , A : List[int ]) -> int :
22
+ # The times a number n occurs in the minimums is |left_bounday-indexof(n)| * |right_bounday-indexof(n)|
23
+ # The total sum is sum([n * |left_bounday - indexof(n)| * |right_bounday - indexof(n)| for n in array]
24
+ res = 0
25
+ stack = [] # non-decreasing
26
+ A = [float (' -inf' )] + A + [float (' -inf' )]
27
+ for i, n in enumerate (A):
28
+ # stack[-1], i is the left and right bounday
29
+ while stack and A[stack[- 1 ]] > n:
30
+ cur = stack.pop()
31
+ res += A[cur] * (i - cur) * (cur - stack[- 1 ])
32
+ stack.append(i)
33
+ return res % (10 ** 9 + 7 )
34
+ ```
You can’t perform that action at this time.
0 commit comments