2537. Count the Number of Good Subarrays #1566
-
Topics: Given an integer array A subarray A subarray is a contiguous non-empty sequence of elements within an array. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to count the number of good subarrays in a given array. A good subarray is defined as one where there are at least ApproachThe approach to solve this problem efficiently involves using a sliding window technique combined with a hash map to track the frequency of elements within the current window. Here are the key steps:
Let's implement this solution in PHP: 2537. Count the Number of Good Subarrays <?php
/**
* @param Integer[] $nums
* @param Integer $k
* @return Integer
*/
function countGood($nums, $k) {
$n = count($nums);
$left = 0;
$right = 0;
$sum_pairs = 0;
$result = 0;
$frequency = array();
while ($left < $n) {
// Expand the window as long as sum_pairs is less than k
while ($right < $n && $sum_pairs < $k) {
$x = $nums[$right];
$current_freq = isset($frequency[$x]) ? $frequency[$x] : 0;
$sum_pairs += $current_freq;
$frequency[$x] = $current_freq + 1;
$right++;
}
// If sum_pairs is at least k, add all subarrays starting at left and ending from right-1 to n-1
if ($sum_pairs >= $k) {
$result += ($n - $right + 1);
}
// Remove the left element from the window
$x = $nums[$left];
$current_freq = $frequency[$x];
$sum_pairs -= ($current_freq - 1);
$frequency[$x]--;
if ($frequency[$x] == 0) {
unset($frequency[$x]);
}
$left++;
}
return $result;
}
// Example 1
$nums1 = array(1,1,1,1,1);
$k1 = 10;
echo countGood($nums1, $k1) . "\n"; // Output: 1
// Example 2
$nums2 = array(3,1,4,3,2,2,4);
$k2 = 2;
echo countGood($nums2, $k2) . "\n"; // Output: 4
?> Explanation:
This approach efficiently counts all valid subarrays in linear time, O(n), by ensuring each element is processed at most twice (once added and once removed from the window). |
Beta Was this translation helpful? Give feedback.
We need to count the number of good subarrays in a given array. A good subarray is defined as one where there are at least
k
pairs of indices(i, j)
such thati < j
andarr[i] == arr[j]
.Approach
The approach to solve this problem efficiently involves using a sliding window technique combined with a hash map to track the frequency of elements within the current window. Here are the key steps:
left
andright
, to explore all possible subarrays.