<p>You are given an integer array <code>nums</code> and two integers <code>minK</code> and <code>maxK</code>.</p>

<p>A <strong>fixed-bound subarray</strong> of <code>nums</code> is a subarray that satisfies the following conditions:</p>

<ul>
	<li>The <strong>minimum</strong> value in the subarray is equal to <code>minK</code>.</li>
	<li>The <strong>maximum</strong> value in the subarray is equal to <code>maxK</code>.</li>
</ul>

<p>Return <em>the <strong>number</strong> of fixed-bound subarrays</em>.</p>

<p>A <strong>subarray</strong> is a <strong>contiguous</strong> part of an array.</p>

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

<pre>
<strong>Input:</strong> nums = [1,3,5,2,7,5], minK = 1, maxK = 5
<strong>Output:</strong> 2
<strong>Explanation:</strong> The fixed-bound subarrays are [1,3,5] and [1,3,5,2].
</pre>

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

<pre>
<strong>Input:</strong> nums = [1,1,1,1], minK = 1, maxK = 1
<strong>Output:</strong> 10
<strong>Explanation:</strong> Every subarray of nums is a fixed-bound subarray. There are 10 possible subarrays.
</pre>

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

<ul>
	<li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>1 &lt;= nums[i], minK, maxK &lt;= 10<sup>6</sup></code></li>
</ul>

class Solution:
    def countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int:
        # another way to solve this problem is to find all of the valid windows
        # and count the valid subarrays

        # now the problem becomes, given an array of nums between minK and maxK
        # find the number of valid subarrays such that its minVal = minK and its maxVal = maxK
        # the idea is still the same as counting the number of valid subarrays that end at a particular index
        def count(a):
            res = 0
            minIdx, maxIdx = None, None
            for i, num in enumerate(a):
                if num == minK:
                    minIdx = i
                if num == maxK:
                    maxIdx = i

                if minIdx is not None and maxIdx is not None:
                    res += min(minIdx, maxIdx) + 1

            return res

        arr = []
        res = 0

        for num in nums:
            if minK <= num <= maxK:
                arr.append(num)
            else:
                res += count(arr)
                arr = []

        # handle the edge case where all of the elements are in a valid range, which causes the previous loop to never execute the else block and count() fn
        
        # if there are left over elements to process, then process it
        if arr:
            res += count(arr)

        return res
504