Skip to content

Commit fce34a3

Browse files
authored
Update 907-sum-of-subarray-minimums.js
1 parent 2808f12 commit fce34a3

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

907-sum-of-subarray-minimums.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,35 @@
1+
2+
/**
3+
* @param {number[]} arr
4+
* @return {number}
5+
*/
6+
const sumSubarrayMins = function (arr) {
7+
const n = arr.length
8+
const mod = 1e9 + 7, stk = []
9+
const left = Array(n), right = Array(n)
10+
for(let i = 0; i< n; i++) {
11+
left[i] = i + 1
12+
right[i] = n - i
13+
}
14+
let res = 0
15+
for(let i = 0; i < n; i++) {
16+
while(stk.length && arr[stk[stk.length - 1]] > arr[i]) {
17+
const idx = stk.pop()
18+
right[idx] = i - idx
19+
}
20+
if (stk.length) left[i] = i - stk[stk.length - 1]
21+
stk.push(i)
22+
23+
}
24+
for(let i = 0; i < n; i++) {
25+
res = (res + arr[i] * left[i] * right[i]) % mod
26+
}
27+
28+
return res
29+
}
30+
31+
// another
32+
133
/**
234
* @param {number[]} arr
335
* @return {number}

0 commit comments

Comments
 (0)