#1438
Medium Algorithms Longest continuous subarray with absolute diff less than or equal to limit
Array Queue Sliding Window Heap (Priority Queue) Ordered Set Monotonic Queue
57.4% acceptance
Feb 25, 2026
4487
226
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.
Solution
Rust
Time O(n²)
Space O(n)
use std::collections::VecDeque;
impl Solution {
pub fn longest_subarray(nums: Vec<i32>, limit: i32) -> i32 {
let mut max_dq: VecDeque<usize> = VecDeque::new(); // decreasing
let mut min_dq: VecDeque<usize> = VecDeque::new(); // increasing
let mut left = 0;
let mut result = 0;
for right in 0..nums.len() {
while !max_dq.is_empty() && nums[*max_dq.back().unwrap()] <= nums[right] {
max_dq.pop_back();
}
max_dq.push_back(right);
while !min_dq.is_empty() && nums[*min_dq.back().unwrap()] >= nums[right] {
min_dq.pop_back();
}
min_dq.push_back(right);
while nums[*max_dq.front().unwrap()] - nums[*min_dq.front().unwrap()] > limit {
left += 1;
if *max_dq.front().unwrap() < left { max_dq.pop_front(); }
if *min_dq.front().unwrap() < left { min_dq.pop_front(); }
}
result = result.max(right - left + 1);
}
result as i32
}
}