class Solution {
public:
int sumSubarrayMins(vector<int>& arr) {
const int MOD = 1e9 + 7;
long res = 0L;
stack<int> stk;
for (int i = 0; i < arr.size(); i++) {
while (!stk.empty() && arr[stk.top()] >= arr[i]) {
int current = stk.top();
stk.pop();
int left = !stk.empty() ? stk.top() : -1;
res += (current - left) * (i - current) * arr[current];
}
stk.push(i);
}
while (!stk.empty()) {
int current = stk.top();
stk.pop();
int left = !stk.empty() ? stk.top() : -1;
res += (current - left) * (arr.size() - current) * arr[current];
}
return res % MOD;
}
};