leetcode_907
Solutions
class Solution {
public:
int sumSubarrayMins(vector<int>& A) {
stack<int> s;
vector<int> sums(A.size());
for (int i = 0; i < A.size(); i++) {
// monotonically increasing stack
while (!s.empty() && A[s.top()] > A[i])
s.pop();
// all numbers left are larger than self
if (s.empty())
sums[i] = (i + 1) * A[i];
else
// counts of subarrays with A[s.top()] as the minimum number and end with A[i] as right most element
// counts of subarrays with A[i] as the minimum number and end with A[i].
// if i - s.top() != 1, these exlucded numbers must be larger than A[i].
sums[i] = sums[s.top()] + (i - s.top()) * A[i];
s.push(i);
}
const long MOD = 1e9 + 7;
long res = 0;
for (auto n : sums)
res = (res + n) % MOD;
return res;
}
};Last updated