Skip to content

Commit 7d06b8c

Browse files
committed
feat: add solution for sliding window maximum
1 parent f0dd83b commit 7d06b8c

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

src/hard/sliding_window_maximum.rs

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,30 @@
11
#![allow(dead_code)]
2-
pub fn max_sliding_window(nums: Vec<i32>, k: i32) -> Vec<i32> {}
2+
pub fn max_sliding_window(nums: Vec<i32>, k: i32) -> Vec<i32> {
3+
let mut result = Vec::new();
4+
let mut window = Vec::new();
5+
6+
for i in 0..nums.len() {
7+
// Remove the first element if it is out of the window
8+
if i >= k as usize && window[0] <= i as i32 - k {
9+
window.remove(0);
10+
}
11+
12+
// Remove all elements smaller than the current one
13+
while window.len() > 0 && nums[*window.last().unwrap() as usize] <= nums[i] {
14+
window.pop();
15+
}
16+
17+
// Add the current element
18+
window.push(i as i32);
19+
20+
// Add the maximum to the result
21+
if i >= k as usize - 1 {
22+
result.push(nums[*window.first().unwrap() as usize]);
23+
}
24+
}
25+
26+
result
27+
}
328

429
#[cfg(test)]
530
mod tests {

0 commit comments

Comments
 (0)