<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:
    def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:
        #subarrays with not 2's - subarrays with only 0's
        # 2 >= right, 1 less than bound
        def count(bound):
            l = 0
            res = 0
            for r in range(len(nums)):
                if nums[r] <= bound:
                    res += r-l+1
                else:
                    l = r+1
            return res

        return count(right) - count(left-1)

        # assume each el is maximum. get prev greater and next greater
        # decreasing stack. pop element if <= cur. 
        # if el not in range continue
        # if el in range left,right  left = stack[-1], right = []
        stack = []
        subarrays = 0
        for i in range(len(nums)+1):
            while stack and (i == len(nums) or nums[stack[-1]] <= nums[i]):
                mid = stack.pop() # end of being max 
                if left <= nums[mid] <= right:
                    l = stack[-1] if stack else -1
                    r = i
                    subarrays += (r-mid)*(mid-l)
            stack.append(i)
        
        return subarrays
24000