Skip to content

Commit 4c9eb87

Browse files
committed
feat(leetcode): 907. Sum of Subarray Minimums : 单调栈
1 parent 105a145 commit 4c9eb87

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* @param {number[]} arr
3+
* @return {number}
4+
*/
5+
const sumSubarrayMins = function (arr) {
6+
const n = arr.length
7+
arr[-1] = arr[n] = -1
8+
let s = [-1]; const l = []; const r = []; let ans = 0
9+
for (let i = 0; i < n; i++) {
10+
while (arr[s[s.length - 1]] >= arr[i]) s.pop()
11+
l[i] = s[s.length - 1]
12+
s.push(i)
13+
}
14+
s = [n]
15+
for (let i = n - 1; i >= 0; i--) {
16+
while (arr[s[s.length - 1]] > arr[i]) s.pop()
17+
r[i] = s[s.length - 1]
18+
s.push(i)
19+
20+
ans = (ans + arr[i] * (i - l[i]) * (r[i] - i)) % (1e9 + 7)
21+
}
22+
return ans
23+
}

0 commit comments

Comments
 (0)