-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sum_of_Subarray_Minimums.java
36 lines (32 loc) · 1.21 KB
/
Sum_of_Subarray_Minimums.java
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
class Solution {
public int sumSubarrayMins(int[] arr) {
final int MOD = 1000000007;
int n = arr.length;
int[] left = new int[n];
int[] right = new int[n];
Stack<Integer> stack = new Stack<>();
// Calculate the number of elements smaller than the current element to the left
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && arr[i] < arr[stack.peek()]) {
stack.pop();
}
left[i] = stack.isEmpty() ? i + 1 : i - stack.peek();
stack.push(i);
}
stack.clear();
// Calculate the number of elements smaller than the current element to the right
for (int i = n - 1; i >= 0; i--) {
while (!stack.isEmpty() && arr[i] <= arr[stack.peek()]) {
stack.pop();
}
right[i] = stack.isEmpty() ? n - i : stack.peek() - i;
stack.push(i);
}
// Calculate the sum of min(b) for each subarray
long result = 0;
for (int i = 0; i < n; i++) {
result = (result + (long) arr[i] * left[i] * right[i]) % MOD;
}
return (int) result;
}
}