-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2962.cpp
More file actions
49 lines (43 loc) · 1.11 KB
/
2962.cpp
File metadata and controls
49 lines (43 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
Approach-1: Brute Force
TC: O(n^2)
SC: O(1)
*/
class Solution {
public:
long long countSubarrays(vector<int>& nums, int k) {
long maxi = *max_element(nums.begin(), nums.end()), count = 0;
for (int i = 0 ; i < nums.size() ; i++) {
long maxOccurrences = 0;
for (int j = i ; j < nums.size() ; j++) {
if (nums[j] == maxi) ++maxOccurrences;
if (maxOccurrences >= k) {
++count;
}
}
}
return count;
}
};
/*
Approach-2: Sliding Window
TC: O(n)
SC: O(1)
*/
class Solution {
public:
long long countSubarrays(vector<int>& nums, int k) {
long long int max_num = *max_element(nums.begin(),nums.end()),count = 0;
long long int left = 0,right = 0,ans = 0;
while(right<nums.size()){
if(nums[right] == max_num)count++;
while(count>=k){
if(nums[left]==max_num)count--;
left++;
ans += nums.size()-right;
}
right++;
}
return ans;
}
};