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.
1def count_subarrays(nums, k):
2 count = max_count = 0
3 max_element = -1
4 j = 0
5
6 for i in range(len(nums)):
7 if nums[i] > max_element:
8 max_element = nums[i]
9 max_count = 1
10 elif nums[i] == max_element:
11 max_count += 1
12
13 while max_count >= k:
14 count += len(nums) - i
15 if nums[j] == max_element:
16 max_count -= 1
17 j += 1
18
19 return count
20
21nums = [1, 3, 2, 3, 3]
22k = 2
23print(count_subarrays(nums, k)) # Output: 6
This Python function uses a sliding window approach to efficiently determine when the current subarray meets the required condition of containing the maximum element at least k
times. The two pointers (i
and j
) allow us to maintain and update the window as needed.
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.
This Python function maintains a two-point tracking mechanism for efficiently checking valid subsequences while managing dynamic changes in maximum element count.