Loading RustViz Engine...
Return maximum values in each sliding window of size k using monotonic queue.
This problem is currently in blueprint template mode. Once the concept foundation is finalized, live in-browser WebAssembly compilation and test assertion runners will be enabled here.
use std::collections::VecDeque;
pub fn max_sliding_window(nums: &[i32], k: usize) -> Vec<i32> {
let mut dq = VecDeque::new();
let mut res = Vec::with_capacity(nums.len().saturating_sub(k) + 1);
for (i, &x) in nums.iter().enumerate() {
if let Some(&front) = dq.front() {
if front + k <= i { dq.pop_front(); }
}
while let Some(&back) = dq.back() {
if nums[back] <= x { dq.pop_back(); } else { break; }
}
dq.push_back(i);
if i + 1 >= k {
res.push(nums[*dq.front().unwrap()]);
}
}
res
}