<p>Given an integer array <code>nums</code> and two integers <code>left</code> and <code>right</code>, return <em>the number of contiguous non-empty <strong>subarrays</strong> such that the value of the maximum array element in that subarray is in the range </em><code>[left, right]</code>.</p>

<p>The test cases are generated so that the answer will fit in a <strong>32-bit</strong> integer.</p>

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

<pre>
<strong>Input:</strong> nums = [2,1,4,3], left = 2, right = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are three subarrays that meet the requirements: [2], [2, 1], [3].
</pre>

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

<pre>
<strong>Input:</strong> nums = [2,9,2,5,6], left = 2, right = 8
<strong>Output:</strong> 7
</pre>

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

<ul>
	<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>
	<li><code>0 &lt;= left &lt;= right &lt;= 10<sup>9</sup></code></li>
</ul>

class Solution {
    void leftsmall(vector<int> &nums, vector<int> &lse)
    {
        stack<int> st;
        for(int i=0;i<nums.size();i++)
        {
            while(!st.empty() && nums[i]>= nums[st.top()])
            {
                st.pop();
            }
            if(!st.empty() )
            {
                lse[i] = st.top();
            }
            else
            {
                lse[i] = -1;
            }
            st.push(i);
        }
    }
    void rightsmall(vector<int> &nums, vector<int> &rse)
    {
        stack<int> st;
        for(int i=nums.size()-1;i>=0;i--)
        {
            while(!st.empty() && nums[i]> nums[st.top()])
            {
                st.pop();
            }
            if(!st.empty())
            {
                rse[i] = st.top();
            }
            else
            {
                rse[i] = nums.size();
            }
            st.push(i);
        }
    }
public:
    int numSubarrayBoundedMax(vector<int>& nums, int left, int right) {
        vector<int> lse(nums.size());
        vector<int> rse(nums.size());
        leftsmall(nums, lse);
        rightsmall(nums, rse);
        int totsub=0;
        for(int i=0;i<nums.size();i++)
        {
            if(nums[i] >=left && nums[i] <=right)
            {
                int l=lse[i];
                int r=rse[i];
                int nosub=(i-l) * (r-i);
                totsub += nosub;
            }
            else
            {
                continue;
            }
        }
        return totsub;
    }
};
62100