⚡Flashcard Drill➔
NeetCode #250LC-2962MediumSliding Window
← Back to All Problems

#250 · #2962 · Count Subarrays Where Max Element Appears at Least K Times(统计最大元素出现至少 K 次的子数组)

📌 Problem Statement & Constraints

You are given an integer array nums and a positive integer k. Return the number of subarrays in which the maximum element of nums appears at least k times. Constraints: 1 <= nums.length <= 10^5, 1 <= nums[i] <= 10^9, 1 <= k <= nums.length.

💡 Core Algorithmic Approaches

  1. Let mx be the maximum of the whole array. Only the occurrences of mx matter.
  2. Maintain a window and a count of mx occurrences inside it, shrinking from the left while the count is at least k.
  3. After shrinking, the minimal window containing k occurrences of mx is [l - 1, r], so every start in [0, l - 1] yields a valid subarray -- contributing l subarrays for this right endpoint.
  4. Summing l over all right endpoints gives the answer.

💻 Benchmark Python3 Implementation

class Solution:
    def countSubarrays(self, nums: List[int], k: int) -> int:
        mx = max(nums)
        l = 0
        cnt = 0                        # occurrences of mx in the window
        res = 0
        for r, x in enumerate(nums):
            if x == mx:
                cnt += 1
            while cnt >= k:            # shrink to the minimal valid window
                if nums[l] == mx:
                    cnt -= 1
                l += 1
            # after shrinking, starts in [0, l-1] all give k occurrences
            res += l
        return res

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): each pointer moves monotonically.
💾 Space Complexity
O(1): two scalars.

⚠️ Interview Pitfalls & Follow-ups

  • Adding 1 per right endpoint instead of l: every valid start position yields a distinct subarray, so the contribution is l.
  • Shrinking while cnt > k instead of cnt >= k: the loop must reduce the count below k so that l - 1 marks the minimal valid window's start.
  • Recomputing max(nums) inside the loop: the global maximum never changes, so compute it once.
  • Counting subarrays where the maximum appears exactly k times: the condition is *at least* k, and the accumulation of l handles that automatically.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Sliding Window Problems

中文速览与面试要点

统计最大元素出现至少 K 次的子数组

给你一个整数数组 nums 和一个正整数 k。请你统计有多少子数组满足:子数组中的 最大元素 在子数组中 至少出现 k 次 。返回满足条件的子数组数目。约束:1 ≤ nums.length ≤ 10^5;1 ≤ nums[i] ≤ 10^9;1 ≤ k ≤ 10^5。

核心要点

  • 关键观察 :全局最大值 mx 一定是任何子数组的最大值。因此问题等价于「统计「mx 出现次数 ≥ k」的子数组数目」。
  • 滑动窗口计数(标准解) :维护窗口内 mx 的个数 cnt 。当 cnt &gt;= k 时收缩左边界,直到 cnt &lt; k 。
  • 累加计数 :收缩结束后,左端点可取 0..l−1 (共 l 个),因为左端点取这些值时窗口内 mx 的个数仍 ≥ k。
  • 为什么左端点范围是 0..l−1 :窗口 [l, r] 的 mx 个数已 &lt; k;而 [l−1, r] 中恰好包含了刚被移出的那个 mx,因此个数 ≥ k。

常见陷阱

  • 收缩条件写成 while cnt &gt; k :会留下 cnt == k 的窗口,导致左端点计数偏移。必须是 cnt &gt;= k ,收缩到 cnt &lt; k 为止。
  • 累加写成 res += l + 1 或 res += r − l + 1 :正确是 res += l (左端点可取 0..l−1)。这是本题最容易搞错的细节,建议用手算小样例验证。
  • 忘记求全局最大值 :必须先求 max(nums) ,它是所有子数组的最大值上界。
  • 收缩时忘记递减 cnt :while 无法退出。

参考实现

class Solution:
    def countSubarrays(self, nums: list[int], k: int) -> int:
        mx = max(nums)
        res = 0
        cnt = 0                 # 窗口内 mx 的个数
        l = 0
        for r, x in enumerate(nums):
            if x == mx:
                cnt += 1
            while cnt >= k:     # 收缩到 mx 个数 < k
                if nums[l] == mx:
                    cnt -= 1
                l += 1
            res += l            # 左端点可取 0..l-1,共 l 个
        return res