File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ fun sumSubarrayMins (_arr : IntArray ): Int {
3+ val mod = 1_000_000_007
4+ var res = 0L
5+ val arr = intArrayOf(Integer .MIN_VALUE ) + _arr + intArrayOf(Integer .MIN_VALUE )
6+ val stack = Stack <Pair <Int , Int >>()
7+
8+ for ((i, n) in arr.withIndex()) {
9+ while (stack.isNotEmpty() && n < stack.peek().second) {
10+ val (j, m) = stack.pop()
11+ val left = if (stack.isNotEmpty()) j - stack.peek().first else j + 1
12+ val right = i - j
13+ res = (res + m.toLong() * left * right) % mod
14+ }
15+ stack.push(i to n)
16+ }
17+
18+ return res.toInt()
19+ }
20+ }
21+
22+ // Another and just a little different solution, you can also only push indices to the stack
23+ class Solution {
24+ fun sumSubarrayMins (arr : IntArray ): Int {
25+ val stack = LinkedList <Int >()
26+ val mod = 1_000_000_007
27+ var res = 0L
28+
29+ for (right in 0 .. arr.size) {
30+ val curVal = if (right < arr.size) arr[right] else 0
31+
32+ while (stack.isNotEmpty() && curVal < arr[stack.peekLast()]) {
33+ val cur = stack.removeLast()
34+ val left = stack.peekLast() ? : - 1
35+ val noOfSubArrs = (cur.toLong() - left) * (right - cur)
36+ res = (res + noOfSubArrs * arr[cur]) % mod
37+ }
38+
39+ stack.addLast(right)
40+ }
41+
42+ return res.toInt()
43+ }
44+ }
You can’t perform that action at this time.
0 commit comments