-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSumOfSubArrayMinimums.java
More file actions
41 lines (33 loc) · 1019 Bytes
/
SumOfSubArrayMinimums.java
File metadata and controls
41 lines (33 loc) · 1019 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package Stacks;
import java.util.Stack;
public class SumOfSubArrayMinimums {
static int MOD = (int) 1e9 + 7;
public static int sumSubArrayMin(int[] arr) {
Stack<Integer> s = new Stack<>();
int n = arr.length;
s.push(-1);
int[] left_smaller = new int[n];
int[] right_smaller = new int[n];
for (int i = 0; i < n; i++) {
left_smaller[i] = -1;
right_smaller[i] = n;
}
int i = 0;
while (i < n) {
while (!s.empty() && s.peek() != -1 && arr[i] < arr[s.peek()]) {
right_smaller[s.peek()] = i;
s.pop();
}
left_smaller[i] = s.peek();
s.push(i);
i++;
}
long answer = 0;
for (i = 0; i < n; ++i) {
long count = (long) (i - left_smaller[i]) * (right_smaller[i] - i) % MOD;
answer += (count * arr[i]) % MOD;
answer %= MOD;
}
return (int) answer;
}
}