2762. Continuous Subarrays #953
-
Topics: You are given a 0-indexed integer array
Return the total number of continuous subarrays. 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 can use the sliding window technique to efficiently calculate the number of continuous subarrays. We'll maintain a valid window where the difference between the maximum and minimum values in the subarray is at most 2. To efficiently track the maximum and minimum values within the current window, we can use two deques (one for the maximum and one for the minimum). Approach
Let's implement this solution in PHP: 2762. Continuous Subarrays <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function continuousSubarrays($nums) {
$n = count($nums);
$left = 0; // Left pointer of the sliding window
$count = 0; // Total count of continuous subarrays
$maxDeque = []; // Deque to store indices for the max value
$minDeque = []; // Deque to store indices for the min value
for ($right = 0; $right < $n; $right++) {
// Maintain the descending order in maxDeque
while (!empty($maxDeque) && $nums[end($maxDeque)] <= $nums[$right]) {
array_pop($maxDeque);
}
$maxDeque[] = $right;
// Maintain the ascending order in minDeque
while (!empty($minDeque) && $nums[end($minDeque)] >= $nums[$right]) {
array_pop($minDeque);
}
$minDeque[] = $right;
// Shrink the window if the condition is violated
while ($nums[$maxDeque[0]] - $nums[$minDeque[0]] > 2) {
$left++;
// Remove indices that are outside the current window
if ($maxDeque[0] < $left) array_shift($maxDeque);
if ($minDeque[0] < $left) array_shift($minDeque);
}
// Add the number of valid subarrays ending at `right`
$count += $right - $left + 1;
}
return $count;
}
// Example usage
$nums1 = [5, 4, 2, 4];
echo continuousSubarrays($nums1) . "\n"; // Output: 8
$nums2 = [1, 2, 3];
echo continuousSubarrays($nums2) . "\n"; // Output: 6
?> Explanation:
Output
Complexity Analysis
This implementation is efficient and works within the constraints provided. |
Beta Was this translation helpful? Give feedback.
We can use the sliding window technique to efficiently calculate the number of continuous subarrays. We'll maintain a valid window where the difference between the maximum and minimum values in the subarray is at most 2. To efficiently track the maximum and minimum values within the current window, we can use two deques (one for the maximum and one for the minimum).
Approach
left
andright
.right
: