i was trying to solve the leetcode problem sum of range minimum i did pretty normal stuff like get the previous smallest numbers index and the next smallest numbers index for each no. stored so that i could find the range length as i – pse[i] and nse[i] – i but.. its not working for [71,55,82,55]
class Solution {
public:
int mod = 1e9 + 7;
int sumSubarrayMins(vector<int>& arr) {
int n = arr.size();
vector<int> nse(n, 0), pse(n,0);
fill(nse, pse, arr, n);
int sum = 0;
for(int i = 0; i<n; i++){
sum=(sum+((nse[i]-i)*(i-pse[i])*arr[i])%mod)%mod;
}
return sum;
}
void fill(vector<int> &nse, vector<int> &pse, vector<int> &arr, int n){
stack<pair<int,int>> st,st2;
pse[0] = -1;
st.push({arr[0],0});
for(int i = 1; i<n ; i++){
while(!st.empty()&&st.top().first>=arr[i]) st.pop();
if(!st.empty()) pse[i] = st.top().second;
else pse[i] = -1;
st.push({arr[i],i});
}
nse[n-1] = n;
st2.push({arr[n-1],n-1});
for(int i = n-2; i>=0;i--){
while(!st2.empty() && st2.top().first>=arr[i]) st2.pop();
if(!st2.empty()) nse[i] = st2.top().second;
else nse[i] = n;
st2.push({arr[i],i});
}
}
};
`
1