Skip to content

Commit cad1ed6

Browse files
authored
Update 907-sum-of-subarray-minimums.js
1 parent ae7d047 commit cad1ed6

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

907-sum-of-subarray-minimums.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,3 +67,38 @@ const sumSubarrayMins = function (arr) {
6767

6868
return res
6969
}
70+
71+
// another
72+
73+
/**
74+
* @param {number[]} arr
75+
* @return {number}
76+
*/
77+
const sumSubarrayMins = function(arr) {
78+
const stk1 = [], stk2 = []
79+
const len = arr.length, mod = 1e9 + 7
80+
const left = new Array(len), right = new Array(len)
81+
for(let i = 0; i < len; i++) {
82+
left[i] = i + 1
83+
right[i] = len - i
84+
}
85+
for(let i = 0; i < len; i++) {
86+
while(stk1.length && arr[stk1[stk1.length - 1]] > arr[i]) {
87+
stk1.pop()
88+
}
89+
left[i] = i - (stk1.length ? stk1[stk1.length - 1] : -1)
90+
stk1.push(i)
91+
92+
while(stk2.length && arr[stk2[stk2.length - 1]] > arr[i]) {
93+
let index = stk2.pop()
94+
right[index] = i - index
95+
}
96+
stk2.push(i)
97+
}
98+
99+
let res = 0
100+
for(let i = 0; i < len; i++) {
101+
res = (res + arr[i] * left[i] * right[i]) % mod
102+
}
103+
return res
104+
};

0 commit comments

Comments
 (0)