907. Sum of Subarray Minimums
Given an array of integers A, find the sum of min(B), where B ranges over every (contiguous) subarray of A.
Since the answer may be large, return the answer modulo 10^9 + 7.
Example 1:
Input: [3,1,2,4]
Output: 17
Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4].
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Sum is 17.
Note:
1 <= A.length <= 30000
1 <= A[i] <= 30000
Approach
需要找规律,找每个数的作用域,也就是这个数的右边第一个小于它的数和左边第一个小于等于它的数
Code
#define modulo 1000000007
class Solution {
public:
int sumSubarrayMins(vector<int> &A) {
int n = A.size();
if (n == 1)
return A[0];
stack<pair<int, int>> st;
vector<int> left(n, -1), right(n, n);
for (int i = 0; i < n; ++i) {
while (!st.empty() && st.top().first > A[i]) {
right[st.top().second] = i;
st.pop();
}
st.push(make_pair(A[i], i));
}
while (!st.empty())st.pop();
for (int i = n - 1; i >= 0; --i) {
while (!st.empty()&&st.top().first>=A[i]){
left[st.top().second]=i;
st.pop();
}
st.push(make_pair(A[i],i));
}
int sum=0;
for(int i=0;i<n;i++){
sum=(sum%modulo+(i-left[i])*(right[i]-i)*A[i]%modulo)%modulo;
}
return sum;
}
};