File tree Expand file tree Collapse file tree 1 file changed +26
-1
lines changed Expand file tree Collapse file tree 1 file changed +26
-1
lines changed Original file line number Diff line number Diff line change 1
1
#![ 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
+ }
3
28
4
29
#[ cfg( test) ]
5
30
mod tests {
You can’t perform that action at this time.
0 commit comments