Skip to content

Commit 10df3ee

Browse files
authored
Create 0907-sum-of-subarray-minimums.kt
1 parent e566b02 commit 10df3ee

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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+
}

0 commit comments

Comments
 (0)