Count Subarrays Where Max Element Appears at Least K Times (LeetCode 2962): Solution and Explanation
Count the subarrays that contain the array's overall maximum value at least k times.
Intuition
The maximum M of the whole array is fixed before we start, so every other value is just filler. All that matters about a subarray is how many copies of M it holds.
Adding elements never removes copies. If nums[j..right] holds at least k copies, so does nums[j-1..right], nums[j-2..right] and so on. For a fixed right end, the valid starts are a prefix 0..L-1 of the array.
A sliding window finds that L. Grow the window to the right, and whenever it holds k copies, move the left edge forward until it holds only k - 1. Now left is the first start that fails, so exactly left starts succeed.
Both pointers only move forward, so the whole scan is linear.
Approach: Sliding window that counts valid starts
- Compute
mx = max(nums). Setcount = 0,left = 0,total = 0(64-bit). - For each
right, add one tocountifnums[right] == mx. - While
count >= k: ifnums[left] == mxsubtract one fromcount, then incrementleft. - Add
lefttototal: starts 0..left-1 all give a subarray ending atrightwith at least k copies. - Return
total.
Step-by-step example
nums = [1,3,2,3,3], k = 2
- mx = 3. right = 0 (1) and right = 1 (3): count reaches 1, below k, so left stays 0 and nothing is added.
- right = 2 (value 2): count is still 1. total stays 0.
- right = 3 (3): count = 2. Shrink: nums[0] = 1 is filler, left = 1; nums[1] = 3 is a copy, count = 1, left = 2. Add 2, total = 2.
- right = 4 (3): count = 2. Shrink: nums[2] = 2, left = 3; nums[3] = 3, count = 1, left = 4. Add 4, total = 6.
- The answer is 6.
Code: Python, Java, C++
1class Solution:
2 def countSubarrays(self, nums: List[int], k: int) -> int:
3 mx = max(nums)
4 total = 0
5 count = left = 0
6 for right, x in enumerate(nums):
7 if x == mx:
8 count += 1
9 while count >= k:
10 if nums[left] == mx:
11 count -= 1
12 left += 1
13 total += left
14 return total1class Solution {
2 public long countSubarrays(int[] nums, int k) {
3 int mx = 0;
4 for (int x : nums) mx = Math.max(mx, x);
5 long total = 0;
6 int count = 0, left = 0;
7 for (int right = 0; right < nums.length; right++) {
8 if (nums[right] == mx) count++;
9 while (count >= k) {
10 if (nums[left] == mx) count--;
11 left++;
12 }
13 total += left;
14 }
15 return total;
16 }
17}1class Solution {
2public:
3 long long countSubarrays(vector<int>& nums, int k) {
4 int mx = *max_element(nums.begin(), nums.end());
5 long long total = 0;
6 int count = 0, left = 0;
7 for (int right = 0; right < (int)nums.size(); right++) {
8 if (nums[right] == mx) count++;
9 while (count >= k) {
10 if (nums[left] == mx) count--;
11 left++;
12 }
13 total += left;
14 }
15 return total;
16 }
17};Time and space complexity
O(n)
right visits each index once and left moves forward at most n times in total.
O(1)
Only the maximum, two pointers, the copy count and the total are stored.
Other approaches
Positions of the maximum (time O(n), space O(n))
Record the indices where M appears. For a right end with at least k copies at or before it, the valid starts are 0..p where p is the k-th most recent position. Sum p + 1 over all right ends.
Count the complement (time O(n), space O(1))
Count subarrays with at most k - 1 copies using a sliding window, then subtract from n(n+1)/2. Same complexity, one extra subtraction.
Common mistakes
- Using the maximum of the current window instead of the global maximum. The problem fixes M as the maximum of the whole array.
- Adding
right - left + 1out of habit. Here the counted subarrays are the ones that start before the window, so the amount to add isleft. - Using a 32-bit total. With n = 10^5 and every value equal the answer is about 5 * 10^9.
- Stopping the shrink at count == k - 1 is right; shrinking further or not at all gives the wrong left.
Frequently asked questions
Why add left and not the window length?
After shrinking, the window [left, right] holds k - 1 copies, so it is not valid. Each start strictly before left adds back at least one copy and makes the subarray valid. There are exactly left such starts.
What if k is larger than the number of copies of the maximum?
count never reaches k, left stays 0, and the answer is 0. No special case is needed.
How is this different from Count Subarrays With Fixed Bounds?
Both count subarrays by their right end. Here the condition is monotone in the start (more elements never hurt), so a single left pointer suffices. Fixed Bounds also has values that break a subarray, which adds a wall position.