Count Subarrays Where Max Element Appears at Least K Times - Problem
You're given an integer array nums and a positive integer k. Your task is to count how many subarrays contain the maximum element of the entire array at least k times.
A subarray is a contiguous sequence of elements within the array. For example, in array [3, 1, 5, 1, 5], the maximum element is 5, and you need to find all subarrays where 5 appears at least k times.
Key Points:
- First identify the maximum element in the entire array
- Then count subarrays where this max element appears โฅ k times
- Consider all possible contiguous subsequences
This problem tests your understanding of subarrays and efficient counting techniques using sliding window approaches.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [1,3,2,3,3], k = 2
โบ
Output:
6
๐ก Note:
Max element is 3. Subarrays with at least 2 occurrences of 3: [3,2,3], [3,2,3,3], [2,3,3], [3,3], [3,2,3,3], [1,3,2,3,3]. Total = 6 subarrays.
example_2.py โ Single Max Element
$
Input:
nums = [1,4,2,1], k = 3
โบ
Output:
0
๐ก Note:
Max element is 4, which appears only once. No subarray can have 4 appearing at least 3 times, so result is 0.
example_3.py โ All Same Elements
$
Input:
nums = [5,5,5], k = 2
โบ
Output:
3
๐ก Note:
Max element is 5 (appears 3 times). Subarrays with at least 2 occurrences: [5,5], [5,5], [5,5,5]. Total = 3 subarrays.
Constraints
- 1 โค nums.length โค 105
- 1 โค nums[i] โค 106
- 1 โค k โค nums.length
- The array always contains at least one element
Visualization
Tap to expand
Understanding the Visualization
1
Identify VIPs
First pass identifies who the VIP guests are (maximum element value)
2
Track Positions
As you scan, keep track of where VIP guests are located
3
Smart Counting
When you have k VIPs in view, count all valid sections ending at current position
4
Efficient Result
Each position processed in O(1) time, total O(n) complexity
Key Takeaway
๐ฏ Key Insight: Instead of checking every section individually (slow), track VIP positions and count valid sections mathematically (fast)!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code