Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- int sumSubarrayMins(vector<int>& arr) {
- long ans=0, mod=int(1e9)+7, sz=arr.size();
- stack< pair<int, int> > s1, s2;
- vector<int> left(sz), right(sz);
- for(int i=0; i<sz; i++){
- int count = 1;
- while(!s1.empty() && s1.top().first >= arr[i]){
- count += s1.top().second;
- s1.pop();
- }
- s1.push({arr[i], count});
- left[i] = count;
- }
- for(int i=sz-1; i>=0; i--){
- int count = 1;
- while(!s2.empty() && s2.top().first > arr[i]){
- count += s2.top().second;
- s2.pop();
- }
- s2.push({arr[i], count});
- right[i] = count;
- }
- for(int i=0; i<sz; i++)
- ans = (ans+(long(left[i])*right[i]*arr[i])%mod)%mod;
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement