Skip to content

Commit 27473b7

Browse files
authored
Create 2962. Count Subarrays Where Max Element Appears at Least K Times (#442)
2 parents 06c8b1c + aee8ffa commit 27473b7

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public:
3+
long long countSubarrays(vector<int>& nums, int k) {
4+
int n=nums.size();
5+
6+
int maxe=*max_element(nums.begin(), nums.end());
7+
8+
long long ans=0;
9+
10+
int count=0; // keep track of count of maxElement in [i,j]
11+
int i=0, j=0;
12+
while(j<n){
13+
count += (nums[j] == maxe);
14+
15+
while(i<=j && count>=k){
16+
ans += (n-j);
17+
18+
count -= (nums[i] == maxe); // shrink window
19+
i++;
20+
}
21+
j++;
22+
}
23+
24+
return ans;
25+
}
26+
};

0 commit comments

Comments
 (0)