<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:
    int sumSubarrayMins(vector<int>& arr)
    {
        size_t n = arr.size();
        size_t mod = 1e9 + 7;

        size_t prev_less[n], next_less[n];
        for (size_t i = 0; i < n; i++) {
            prev_less[i] = i + 1;
            next_less[i] = n - i;
        }

        stack<size_t> stk1, stk2;
        for (size_t i = 0; i < n; i++) {
            while (!stk1.empty() && arr[stk1.top()] > arr[i])
                stk1.pop();
            prev_less[i] = stk1.empty() ? i + 1 : i - stk1.top();
            stk1.push(i);

            // while (!stk2.empty() && arr[stk2.top()] > arr[i]) {
            //     size_t idx = stk2.top();
            //     stk2.pop();
            //     next_less[idx] = i - idx;
            // }

            // stk2.push(i);
        }

        for (int i = n - 1; i >= 0; i--) {
            while (!stk2.empty() && arr[stk2.top()] >= arr[i])
                stk2.pop();
            next_less[i] = stk2.empty() ? n - i : stk2.top() - i;
            stk2.push(i);
        }

        size_t ans = 0;

        for (size_t i = 0; i < n; i++)
            ans = (ans + (prev_less[i] * next_less[i] * arr[i])) % mod;

        for (int i = 0; i < n; i++)
            cout << prev_less[i] << " ";

        cout << endl;

        for (int i = 0; i < n; i++)
            cout << next_less[i] << " ";
        return ans;
    }
};
44500