<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:
        n = len(nums)
        max_num = max(nums)

        # option1: sliding window 2n
        elem_count = {}
        count = 0
        s = 0
        for e in range(n):
            elem_count[nums[e]] = elem_count.get(nums[e], 0) + 1
            while elem_count.get(max_num, 0) >= k:
                count += (n-e)
                elem_count[nums[s]] -= 1
                s += 1
        return count

        # option2: prefix_sum nlogn
        # prefix_sum = [0] * (n + 1)
        # for i in range(n):
        #     if nums[i] >= max_num:
        #         prefix_sum[i + 1] = prefix_sum[i] + 1
        #     else:
        #         prefix_sum[i + 1] = prefix_sum[i]
        # count = 0
        # for s in range(n):
        #     target = prefix_sum[s] + k
        #     e = bisect.bisect_left(prefix_sum, target, s + 1)
        #     if e <= n:
        #         count += (n - e + 1)
        # return count

1023