求所有子数组的最小值之和,单调栈处理每个值作为最小值的区间,然后统计。
code
class Solution {
public:
int sumSubarrayMins(vector<int>& A) {
int n=A.size();
stack<int> s;
vector<int> l(n,0),r(n,0);
for(int i=0;i<n;i++){
while(!s.empty() && A[s.top()]>A[i]){
s.pop();
}
if(s.empty()){
l[i]=0;
}else{
l[i]=s.top()+1;
}
s.push(i);
}
while(!s.empty()){
s.pop();
}
for(int i=n-1;i>=0;i--){
while(!s.empty() && A[s.top()]>=A[i]){
s.pop();
}
if(s.empty()){
r[i]=n-1;
}else{
r[i]=s.top()-1;
}
s.push(i);
}
long long ans=0;
long long mod=1e9+7;
for(int i=0;i<n;i++){
ans+=1ll*(r[i]-l[i]+1)*A[i];
ans+=1ll*(r[i]-i)*(i-l[i])*A[i];
ans%=mod;
}
return (int)ans;
}
};