题目链接:https://leetcode.cn/problems/sum-of-subarray-minimums/
题意:
给定一个数组,让你求子数组最小值的和,复杂度O(N)
思路:
单调栈(获得每个位置左边比它小且离它最近的数,右边比它小且离它最近的数,那么在这之间它本身就是区间最小值)
class Solution {
public:
int sumSubarrayMins(vector<int>& arr) {
long long mod=1000000000+7;
int st[30005];
int ans[30005][2];
int n=arr.size();
int r=0,cur;
for(int i=0;i<n;i++)
{
while(r>0&&arr[st[r-1]]>=arr[i])
{
cur=st[--r];
ans[cur][0]=r>0?st[r-1]:-1;
ans[cur][1]=i;
}
st[r++]=i;
}
while(r>0)
{
cur=st[--r];
ans[cur][1]=n;
ans[cur][0]=r>0?st[r-1]:-1;
}
long long res=0;
for(int i=0;i<n;i++)
{
res=(res+(long long)arr[i]*(i-ans[i][0])*(ans[i][1]-i))%mod;//同余定理(重要)(每两数相加再取模=一群数相加取模)
}
return res;
}
};
标签:arr,cur,int,long,st,最小值,数组,ans,单调
From: https://www.cnblogs.com/benscode/p/18665385