2444. Count Subarrays With Fixed Bounds #1609
-
Topics: You are given an integer array A fixed-bound subarray of
Return the number of fixed-bound subarrays. A subarray is a contiguous part of 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 subarrays where the minimum value is exactly Approach
Let's implement this solution in PHP: 2444. Count Subarrays With Fixed Bounds <?php
/**
* @param Integer[] $nums
* @param Integer $minK
* @param Integer $maxK
* @return Integer
*/
function countSubarrays($nums, $minK, $maxK) {
$start = 0;
$lastMin = -1;
$lastMax = -1;
$count = 0;
$n = count($nums);
for ($i = 0; $i < $n; $i++) {
$num = $nums[$i];
if ($num < $minK || $num > $maxK) {
$start = $i + 1;
$lastMin = -1;
$lastMax = -1;
} else {
if ($num == $minK) {
$lastMin = $i;
}
if ($num == $maxK) {
$lastMax = $i;
}
if ($lastMin != -1 && $lastMax != -1) {
$count += max(0, min($lastMin, $lastMax) - $start + 1);
}
}
}
return $count;
}
// Example 1
$nums = array(1, 3, 5, 2, 7, 5);
$minK = 1;
$maxK = 5;
echo countSubarrays($nums, $minK, $maxK) . "\n"; // Output: 2
// Example 2
$nums = array(1, 1, 1, 1);
$minK = 1;
$maxK = 1;
echo countSubarrays($nums, $minK, $maxK) . "\n"; // Output: 10
?> Explanation:
This approach efficiently counts the valid subarrays in linear time, ensuring optimal performance even for large input sizes. |
Beta Was this translation helpful? Give feedback.
We need to count the number of subarrays where the minimum value is exactly
minK
and the maximum value is exactlymaxK
. These subarrays must be contiguous and all elements within them must lie betweenminK
andmaxK
inclusive.Approach
[minK, maxK]
. If an element outside these bounds is encountered, the window is reset starting from the next element.minK
andmaxK
were encountered. This helps in determining the valid subarrays ending at each position.