class Solution {
public int sumSubarrayMins(int[] arr) {
int MOD = 1_000_000_007;
int n = arr.length;
int[] left = new int[n];
int[] right = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && arr[stack.peek()] > arr[i]) {
stack.pop();
}
left[i] = stack.isEmpty() ? -1 : stack.peek();
stack.push(i);
}
stack.clear();
for (int i = n - 1; i >= 0; i--) {
while (!stack.isEmpty() && arr[stack.peek()] >= arr[i]) {
stack.pop();
}
right[i] = stack.isEmpty() ? n : stack.peek();
stack.push(i);
}
long result = 0;
for (int i = 0; i < n; i++) {
int leftCount = i - left[i] - 1;
int rightCount = right[i] - i;
long part1 = ((long) arr[i] * leftCount % MOD) * rightCount % MOD;
long part2 = ((long) arr[i] * rightCount) % MOD;
long contribution = (part1 + part2) % MOD;
result = (result + contribution) % MOD;
}
return (int) result;
}
}