1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit #273
-
Topics: Given an array of integers Example 1:
Example 2:
Example 3:
Example 4:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The problem asks for the longest subarray where the absolute difference between any two elements is less than or equal to a given Key Points:
Approach:
Plan:
Let's implement this solution in PHP: 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit <?php
/**
* @param Integer[] $nums
* @param Integer $limit
* @return Integer
*/
function longestSubarray($nums, $limit) {
$ans = 1;
$minQ = new SplDoublyLinkedList();
$maxQ = new SplDoublyLinkedList();
for ($l = 0, $r = 0; $r < count($nums); ++$r) {
while (!$minQ->isEmpty() && $minQ->top() > $nums[$r])
$minQ->pop();
$minQ->push($nums[$r]);
while (!$maxQ->isEmpty() && $maxQ->top() < $nums[$r])
$maxQ->pop();
$maxQ->push($nums[$r]);
while ($maxQ->bottom() - $minQ->bottom() > $limit) {
if ($minQ->bottom() == $nums[$l])
$minQ->shift();
if ($maxQ->bottom() == $nums[$l])
$maxQ->shift();
++$l;
}
$ans = max($ans, $r - $l + 1);
}
return $ans;
}
// Example usage:
$nums = [8,2,4,7];
$limit = 4;
echo longestSubarray($nums, $limit) . "\n"; // Output: 2
$nums = [10,1,2,4,7,2];
$limit = 5;
echo longestSubarray($nums, $limit) . "\n"; // Output: 4
$nums = [4,2,2,2,4,4,2,2];
$limit = 0;
echo longestSubarray($nums, $limit) . "\n"; // Output: 3
?> Explanation:
Example Walkthrough:Example 1:Input: nums = [8, 2, 4, 7], limit = 4
Example 2:Input: nums = [10, 1, 2, 4, 7, 2], limit = 5
Time Complexity:
Output for Example:For Example 1:
For Example 2:
This approach efficiently finds the longest subarray that satisfies the condition using a sliding window technique with two deques. The sliding window ensures that we only need to traverse the array once, making the solution scalable for large inputs. The deques allow constant-time access to the maximum and minimum values, making this approach optimal for the problem constraints. |
Beta Was this translation helpful? Give feedback.
The problem asks for the longest subarray where the absolute difference between any two elements is less than or equal to a given
limit
. This requires efficiently finding subarrays that satisfy this condition. The challenge lies in the size of the input (nums.length
up to _**10^5)), which necessitates an efficient solution that avoids brute force methods.Key Points:
l
andr
), wherel
is the left pointer andr
is the right pointer.