<p>Given an array of integers arr, find the sum of <code>min(b)</code>, where <code>b</code> ranges over every (contiguous) subarray of <code>arr</code>. Since the answer may be large, return the answer <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> arr = [3,1,2,4]
<strong>Output:</strong> 17
<strong>Explanation:</strong> 
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.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> arr = [11,81,94,43,3]
<strong>Output:</strong> 444
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= arr.length &lt;= 3 * 10<sup>4</sup></code></li>
	<li><code>1 &lt;= arr[i] &lt;= 3 * 10<sup>4</sup></code></li>
</ul>

class Solution {
public:
    vector<int> recur(vector<int>& arr){
        int n=arr.size();
        stack<int>s1;
        vector<int>v1(n,0);
        for(int j=n-1;j>=0;j--){
            if(s1.size()==0){
                v1[j]=-1;
                s1.push(j);
            }
            else{
                while(s1.size()>0 && arr[j]<=arr[s1.top()]){
                      s1.pop();
                }
                if(s1.size()>0){
                    v1[j]=s1.top();
                }
                else{
                    v1[j]=-1;
                }
                s1.push(j);
            }
        }
        return v1;
    }
    int recur1(vector<int>&v1,int j,vector<int>& arr,vector<int>&v2){
        if(v1[j]==-1){
            int j1=arr.size();
            int e=1e9+7;
            int k=(((j1-j))%e*(arr[j])%e)%e;
            //cout<<k<<endl;
            v2[j]=k;
            return v2[j];
        }
        else if(v2[j]!=-1){
            return v2[j];
        }
        else{
            int j1=v1[j];
            int e=1e9+7;
            int k=(((j1-j))%e*(arr[j])%e)%e;
            //cout<<k<<endl;
            k=(k+recur1(v1,j1,arr,v2))%e;
            v2[j]= k;
            return v2[j];
        }
    }
    int sumSubarrayMins(vector<int>& arr) {
        int ans=0;
        int e=1e9+7;
        vector<int>v1=recur(arr);
        vector<int>v2(arr.size(),-1);
        for(int i=0;i<arr.size();i++){
            ans=(ans+recur1(v1,i,arr,v2))%e;
            //cout<<ans<<endl;
        }
        return ans;
    }
};
46200