File tree 2 files changed +44
-0
lines changed
2 files changed +44
-0
lines changed Original file line number Diff line number Diff line change 717
717
904|[ Fruit Into Baskets] ( ./0904-fruit-into-baskets.js ) |Medium|
718
718
905|[ Sort Array By Parity] ( ./0905-sort-array-by-parity.js ) |Easy|
719
719
906|[ Super Palindromes] ( ./0906-super-palindromes.js ) |Hard|
720
+ 907|[ Sum of Subarray Minimums] ( ./0907-sum-of-subarray-minimums.js ) |Medium|
720
721
909|[ Snakes and Ladders] ( ./0909-snakes-and-ladders.js ) |Medium|
721
722
912|[ Sort an Array] ( ./0912-sort-an-array.js ) |Medium|
722
723
914|[ X of a Kind in a Deck of Cards] ( ./0914-x-of-a-kind-in-a-deck-of-cards.js ) |Medium|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 907. Sum of Subarray Minimums
3
+ * https://leetcode.com/problems/sum-of-subarray-minimums/
4
+ * Difficulty: Medium
5
+ *
6
+ * Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous)
7
+ * subarray of arr. Since the answer may be large, return the answer modulo 109 + 7.
8
+ */
9
+
10
+ /**
11
+ * @param {number[] } arr
12
+ * @return {number }
13
+ */
14
+ var sumSubarrayMins = function ( arr ) {
15
+ const MOD = 1e9 + 7 ;
16
+ const left = new Array ( arr . length ) ;
17
+ const right = new Array ( arr . length ) ;
18
+ const stack = [ ] ;
19
+
20
+ for ( let i = 0 ; i < arr . length ; i ++ ) {
21
+ while ( stack . length && arr [ stack [ stack . length - 1 ] ] > arr [ i ] ) {
22
+ stack . pop ( ) ;
23
+ }
24
+ left [ i ] = stack . length ? i - stack [ stack . length - 1 ] : i + 1 ;
25
+ stack . push ( i ) ;
26
+ }
27
+
28
+ stack . length = 0 ;
29
+ for ( let i = arr . length - 1 ; i >= 0 ; i -- ) {
30
+ while ( stack . length && arr [ stack [ stack . length - 1 ] ] >= arr [ i ] ) {
31
+ stack . pop ( ) ;
32
+ }
33
+ right [ i ] = stack . length ? stack [ stack . length - 1 ] - i : arr . length - i ;
34
+ stack . push ( i ) ;
35
+ }
36
+
37
+ let result = 0 ;
38
+ for ( let i = 0 ; i < arr . length ; i ++ ) {
39
+ result = ( result + arr [ i ] * left [ i ] * right [ i ] ) % MOD ;
40
+ }
41
+
42
+ return result ;
43
+ } ;
You can’t perform that action at this time.
0 commit comments