Skip to content

Commit 6550b7e

Browse files
authored
Update 907-sum-of-subarray-minimums.js
1 parent 2168220 commit 6550b7e

File tree

1 file changed

+22
-26
lines changed

1 file changed

+22
-26
lines changed

907-sum-of-subarray-minimums.js

Lines changed: 22 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,33 @@
11
/**
2-
* @param {number[]} A
2+
* @param {number[]} arr
33
* @return {number}
44
*/
5-
const sumSubarrayMins = function (A) {
6-
const n = A.length
7-
const s1 = []
8-
const s2 = []
9-
const left = new Array(n)
10-
const right = new Array(n)
11-
12-
for (let i = 0; i < n; i++) {
13-
let count = 1
14-
while (s1.length && s1[s1.length - 1][0] > A[i]) {
15-
count += s1.pop()[1]
5+
const sumSubarrayMins = function(arr) {
6+
const n = arr.length, s1 = [], s2 = [], left = Array(n), right = Array(n)
7+
for(let i = 0; i < n; i++) {
8+
let cnt = 1
9+
while(s1.length && s1[s1.length - 1][0] > arr[i]) {
10+
cnt += s1.pop()[1]
1611
}
17-
left[i] = count
18-
s1.push([A[i], count])
12+
left[i] = cnt
13+
s1.push([arr[i], cnt])
1914
}
20-
21-
for (let i = n - 1; i >= 0; i--) {
22-
let count = 1
23-
// use ">=" to deal with duplicate elements
24-
while (s2.length && s2[s2.length - 1][0] >= A[i]) {
25-
count += s2.pop()[1]
15+
16+
for(let i = n - 1; i >= 0; i--) {
17+
let cnt = 1
18+
while(s2.length && s2[s2.length - 1][0] >= arr[i]) {
19+
cnt += s2.pop()[1]
2620
}
27-
right[i] = count
28-
s2.push([A[i], count])
21+
right[i] = cnt
22+
s2.push([arr[i], cnt])
2923
}
30-
3124
let res = 0
3225
const mod = 1e9 + 7
33-
for (let i = 0; i < n; i++) {
34-
res = (res + left[i] * A[i] * right[i]) % mod
26+
for(let i = 0; i < n; i++) {
27+
// left[i] number of starting positions
28+
// right[i] number of ending positions
29+
res = (res + arr[i] * left[i] * right[i]) % mod
3530
}
31+
3632
return res
37-
}
33+
};

0 commit comments

Comments
 (0)