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
- Let
mxbe the maximum of the whole array. Only the occurrences ofmxmatter. - Maintain a window and a count of
mxoccurrences inside it, shrinking from the left while the count is at leastk. - After shrinking, the minimal window containing
koccurrences ofmxis[l - 1, r], so every start in[0, l - 1]yields a valid subarray -- contributinglsubarrays for this right endpoint. - Summing
lover 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 isl. - Shrinking while
cnt > kinstead ofcnt >= k: the loop must reduce the count belowkso thatl - 1marks 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 oflhandles that automatically.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Sliding Window Problems
#219 · #219Contains Duplicate II#220 · #121Best Time to Buy and Sell Stock#221 · #2379Minimum Recolors to Get K Consecutive Black Blocks#222 · #1984Minimum Difference Between Highest and Lowest of K Scores#223 · #1343Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold#224 · #1052Grumpy Bookstore Owner
中文速览与面试要点
统计最大元素出现至少 K 次的子数组
给你一个整数数组 nums 和一个正整数 k。请你统计有多少子数组满足:子数组中的 最大元素 在子数组中 至少出现 k 次 。返回满足条件的子数组数目。约束:1 ≤ nums.length ≤ 10^5;1 ≤ nums[i] ≤ 10^9;1 ≤ k ≤ 10^5。
核心要点
- 关键观察 :全局最大值 mx 一定是任何子数组的最大值。因此问题等价于「统计「mx 出现次数 ≥ k」的子数组数目」。
- 滑动窗口计数(标准解) :维护窗口内 mx 的个数 cnt 。当 cnt >= k 时收缩左边界,直到 cnt < k 。
- 累加计数 :收缩结束后,左端点可取 0..l−1 (共 l 个),因为左端点取这些值时窗口内 mx 的个数仍 ≥ k。
- 为什么左端点范围是 0..l−1 :窗口 [l, r] 的 mx 个数已 < k;而 [l−1, r] 中恰好包含了刚被移出的那个 mx,因此个数 ≥ k。
常见陷阱
- 收缩条件写成 while cnt > k :会留下 cnt == k 的窗口,导致左端点计数偏移。必须是 cnt >= k ,收缩到 cnt < 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