2962. Count Subarrays Where Max Element Appears at Least K Times #1621
-
Topics: You are given an integer array Return the number of subarrays where the maximum element of A subarray is a contiguous sequence of elements within an array. Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to count the number of subarrays where the maximum element of the given array appears at least K times. The approach involves identifying the positions of the maximum element and using these positions to efficiently calculate valid subarrays. Approach
Let's implement this solution in PHP: 2962. Count Subarrays Where Max Element Appears at Least K Times <?php
/**
* @param Integer[] $nums
* @param Integer $k
* @return Integer
*/
function countSubarrays($nums, $k) {
$max = max($nums);
$indices = array();
foreach ($nums as $i => $num) {
if ($num == $max) {
$indices[] = $i;
}
}
$m = count($indices);
if ($m < $k) {
return 0;
}
$n = count($nums);
$total = 0;
for ($j = $k - 1; $j < $m; $j++) {
$i = $j - $k + 1;
$prev = ($i > 0) ? $indices[$i - 1] : -1;
$left = $indices[$i] - $prev;
$right = $n - $indices[$j];
$total += $left * $right;
}
return $total;
}
// Example Usage:
echo countSubarrays([1,3,2,3,3], 2); // Output: 6
echo "\n";
echo countSubarrays([1,4,2,1], 3); // Output: 0
?> Explanation:
This approach efficiently counts all valid subarrays using the positions of the maximum element, ensuring that each subarray meets the requirement of containing the maximum element at least K times. The complexity is linear with respect to the number of elements in the array, making it efficient for large input sizes. |
Beta Was this translation helpful? Give feedback.
We need to count the number of subarrays where the maximum element of the given array appears at least K times. The approach involves identifying the positions of the maximum element and using these positions to efficiently calculate valid subarrays.
Approach