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.
1using System;
2
3public class Solution {
4 public int CountSubarrays(int[] nums, int k) {
5 int count = 0, maxCount = 0, maxElement = -1, j = 0;
6 int n = nums.Length;
7 for (int i = 0; i < n; i++) {
8 if (nums[i] > maxElement) {
9 maxElement = nums[i];
10 maxCount = 1;
11 } else if (nums[i] == maxElement) {
12 maxCount++;
13 }
14 while (maxCount >= k) {
15 count += n - i;
16 if (nums[j] == maxElement) {
17 maxCount--;
18 }
19 j++;
20 }
21 }
22 return count;
23 }
24
25 public static void Main() {
26 Solution sol = new Solution();
27 int[] nums = {1, 3, 2, 3, 3};
28 int k = 2;
29 Console.WriteLine(sol.CountSubarrays(nums, k)); // Output: 6
30 }
31}
The C# code operation involves tracking the maximum and counting valid subarrays. The process ensures the output subarrays contain the maximum element the specified number of times, utilizing a sliding window and two-pointer strategy.
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 C code uses two pointers (left
and right
) to validate subarrays. When a maximum condition changes, the calculation restarts, which ensures only subarrays with the required maximum occurrence are considered.