<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 {
private:
    vector<int> prefixSum;
    int n, k, maxElement;
    
    long long countSubarraysRecursive(int start, int end) {
        if (start > end) return 0;
        if (start == end) return (prefixSum[end + 1] - prefixSum[start] >= k) ? 1 : 0;
        
        int mid = start + (end - start) / 2;
        long long leftCount = countSubarraysRecursive(start, mid);
        long long rightCount = countSubarraysRecursive(mid + 1, end);
        
        long long crossCount = 0;
        int right = mid + 1;
        for (int left = start; left <= mid; left++) {
            while (right <= end && prefixSum[right + 1] - prefixSum[left] < k) {
                right++;
            }
            if (right <= end) {
                crossCount += end - right + 1;
            }
        }
        
        return leftCount + rightCount + crossCount;
    }

public:
    Solution(){
         std::ios_base::sync_with_stdio(false);
        std::cin.tie(nullptr);
        std::cout.tie(nullptr);
    }
    long long countSubarrays(vector<int>& nums, int k) {
        n = nums.size();
        this->k = k;
        maxElement = *max_element(nums.begin(), nums.end());
        
        prefixSum.resize(n + 1, 0);
        for (int i = 0; i < n; i++) {
            prefixSum[i + 1] = prefixSum[i] + (nums[i] == maxElement);
        }
        
        return countSubarraysRecursive(0, n - 1);
    }
};
126200