File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff 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+ } ;
You can’t perform that action at this time.
0 commit comments