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.
public class Solution {
public int CountSubarrays(int[] nums, int k) {
int count = 0, left = 0, maxElement = 0, maxCount = 0;
for (int right = 0; right < nums.Length; right++) {
if (nums[right] > maxElement) {
maxElement = nums[right];
maxCount = 1;
} else if (nums[right] == maxElement) {
maxCount++;
}
while (maxCount >= k) {
count += nums.Length - right;
if (nums[left++] == maxElement) {
maxCount--;
}
}
}
return count;
}
public static void Main() {
Solution sol = new Solution();
int[] nums = {1, 3, 2, 3, 3};
int k = 2;
Console.WriteLine(sol.CountSubarrays(nums, k)); // Output: 6
}
}
The C# algorithm operates by controlling the sequence using dynamics between the two-pointer configuration and the maximum value encountered, ensuring it’s logged correctly through controlled increments.