<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:
        C = Counter(nums)
        K = max(C)
        L = C.total()

        if C[K] < k: return 0

        '''
        all subarrays that have at least k occurences of K.
        we start from i,j=0,0.  move j until we have k occurences.
        now we start counting results.
        there are L-j more results when i=0 that satisfy the k requirement.
        we now move i forward until we find a K, incrementing the result.
        now we reduce k occurences and repeat with j.
        '''
        result=0
        i,j,h=0,0,0
        seen_k=0
        next_K=[]
        while i < L:
            # move j to k'th K
            while j < L:
                if nums[j]==K:
                    next_K.append(j)
                    seen_k+=1
                if seen_k==k:
                    break
                j+=1
            # didn't see enough K's, stop here.
            if seen_k<k: 
                break
            
            # add to the result distance from 1st K to where we started
            result+=((next_K[h]+1-i)*(L-j))

            # decrease seen_k, as we have just skipped the 1st one
            seen_k-=1

            # move left just after the 1st K
            i=next_K[h]+1

            # move j so it doesn't repeat the K it is on right now
            j+=1

            h+=1


        return result

951