LeetCode solutions

3213. Count Subarrays Where Max Element Appears at Least K Times

My accepted Python solution to LeetCode problem 3213, Count Subarrays Where Max Element Appears at Least K Times, running in 90ms.

  • Difficulty: Medium
  • Python
  • Runtime 90ms
  • Memory 29.5MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 90ms, memory 29.5MB, accepted 2026-01-02.

python
class Solution:
    def countSubarrays(self, nums: List[int], k: int) -> int:
        max_elem = max(nums)
        n = len(nums)
        count = 0
        left = 0
        result = 0
        
        for right in range(n):
            if nums[right] == max_elem:
                count += 1
            
            while count >= k:
                result += n - right
                if nums[left] == max_elem:
                    count -= 1
                left += 1
        
        return result

Source