<p>You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>.</p>

<p>Return <em>the number of subarrays where the <strong>maximum</strong> element of </em><code>nums</code><em> appears <strong>at least</strong> </em><code>k</code><em> times in that subarray.</em></p>

<p>A <strong>subarray</strong> is a contiguous sequence of elements within an array.</p>

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

<pre>
<strong>Input:</strong> nums = [1,3,2,3,3], k = 2
<strong>Output:</strong> 6
<strong>Explanation:</strong> The subarrays that contain the element 3 at least 2 times are: [1,3,2,3], [1,3,2,3,3], [3,2,3], [3,2,3,3], [2,3,3] and [3,3].
</pre>

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

<pre>
<strong>Input:</strong> nums = [1,4,2,1], k = 3
<strong>Output:</strong> 0
<strong>Explanation:</strong> No subarray contains the element 4 at least 3 times.
</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>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li>
	<li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li>
</ul>

class Solution:
    def countSubarrays(self, nums: List[int], k: int) -> int:
        # sliding window

        biggest = max(nums) # find biggest element in nums

        l, count, biggestCount = 0, 0, 0

        for r in range(len(nums)):
            if nums[r] == biggest: # if current element is the same as biggest 
                biggestCount += 1 # increment the freq of the max element
            while biggestCount >= k: # shrink the window until we atleast have biggest appear k times
                if nums[l] == biggest: 
                    biggestCount -= 1 
                l += 1 # shrink window
        
            count += l # count number of subarrays #
            # The index variable start accounts for multiple starting positions for valid subarrays (where the frequency of the maximum is at least k) at the current ending position (let's track this by index variable end). By adding start to the answer, we ensure that we account for all valid subarrays ending at the current index end. This is because of the fact that for a given ending position end, there exist start + 1 possible starting positions, each contributing to a valid subarray.
        
        return count
856