<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> findRightSmallerIndex(vector<int>& arr) {
        vector<int> next_smaller_el(
            arr.size(), arr.size()); 
        stack<int> st;
        int n = arr.size();

        for (int i = n - 1; i >= 0; i--) {
            int curr = arr[i];

            while (!st.empty() && arr[st.top()] >= curr) {
                st.pop();
            }
            int ans = st.empty() ? n : st.top();
            next_smaller_el[i] = ans;
            st.push(i);
        }
        return next_smaller_el;
    }

    vector<int> findLeftSmallerIndex(vector<int>& arr) {
        vector<int> prev_smaller_el(arr.size(), -1);
        stack<int> st;
        int n = arr.size();

        for (int i = 0; i < n; i++) {
            int curr = arr[i];

            while (!st.empty() && arr[st.top()] > curr) {
                st.pop();
            }
            int ans = st.empty() ? -1 : st.top();
            prev_smaller_el[i] = ans;
            st.push(i);
        }
        return prev_smaller_el;
    }

    int solve(vector<int>& arr) {
        int ans = 0;
        int n = arr.size();
        const int MOD = 1e9 + 7; 
        
        vector<int> pse = findLeftSmallerIndex(arr);
        vector<int> nse = findRightSmallerIndex(arr);

        // multiplying both left and right distances(range)
        for (int i = 0; i < n; i++) {
            long long left_dist = i - pse[i];
            long long right_dist = nse[i] - i;
            long long contribution = (arr[i] * left_dist % MOD) * right_dist % MOD;
            ans = (ans + contribution) % MOD;
        }
        return ans;
    }

    int sumSubarrayMins(vector<int>& arr) {
        // brute
        // int n = arr.size();
        // int mn = 0, ans = 0;
        // for(int i=0; i<n; i++){
        //     mn = INT_MAX;
        //     for(int j=i; j<n; j++){
        //         mn = min(mn, arr[j]);
        //         ans += mn;
        //     }
        // }
        // return ans;

        // optimal using monotonic stack range
        return solve(arr);
    }
};
45900