Sponsored
Sponsored
This approach utilizes the sliding window technique to efficiently count subarrays that satisfy the given condition. By maintaining a window and a count of the occurrences of the maximum element within that window, we can determine the valid subarrays as we expand and contract the window.
Time Complexity: O(n), where n is the number of elements in nums.
Space Complexity: O(1), only constant space is used for variables.
1#include <vector>
2#include <iostream>
3using namespace std;
4
5int countSubarrays(vector<int>& nums, int k) {
6 int count = 0, max_count = 0, max_element = -1, j = 0;
7
8 for (int i = 0; i < nums.size(); i++) {
9 if (nums[i] > max_element) {
10 max_element = nums[i];
11 max_count = 1;
12 } else if (nums[i] == max_element) {
13 max_count++;
14 }
15
16 while (max_count >= k) {
17 count += nums.size() - i;
18 if (nums[j] == max_element) {
19 max_count--;
20 }
21 j++;
22 }
23 }
24
25 return count;
26}
27
28int main() {
29 vector<int> nums = {1, 3, 2, 3, 3};
30 int k = 2;
31 cout << countSubarrays(nums, k) << endl; // Output: 6
32 return 0;
33}
Similar to C, this C++ implementation utilizes a sliding window to maintain a current maximum and its count. By employing two pointers, it efficiently calculates the number of valid subarrays containing at least k
occurrences of the current maximum element.
This strategy involves iterating through the array with two pointers, resetting conditions when new maximum elements are encountered and calculating valid subarrays based on maximum occurrence counts.
Time Complexity: O(n), as we process each element in nums.
Space Complexity: O(1), no extra space besides pointer variables.
The Java implementation tracks maximum occurrences similarly, effectively managing reset mechanisms when the current subarray disconnects from the given constraints.