File tree 1 file changed +15
-2
lines changed
1 file changed +15
-2
lines changed Original file line number Diff line number Diff line change
1
+ use std:: collections:: VecDeque ;
2
+
1
3
pub struct Solution { }
2
4
3
5
impl Solution {
@@ -14,10 +16,21 @@ impl Solution {
14
16
同时需要再判断,如果 queue 中的第一个元素(nums 索引,对应最大值)超过了范围,则删除最大值。
15
17
*/
16
18
let mut max_cache = vec ! [ 0 ; nums. len( ) ] ;
19
+ let mut queue = VecDeque :: new ( ) ;
17
20
for ( i, n) in nums. iter ( ) . enumerate ( ) . rev ( ) {
18
- let res_vec = max_cache[ ( i + 1 ) ..( i + 1 + k as usize ) . min ( nums. len ( ) ) ] . to_vec ( ) ;
19
- let res = res_vec. iter ( ) . max ( ) . unwrap_or ( & 0 ) + * n;
21
+ let res = * n
22
+ + queue
23
+ . front ( )
24
+ . and_then ( |x| max_cache. iter ( ) . nth ( * x) )
25
+ . unwrap_or ( & 0 ) ;
20
26
max_cache[ i] = res;
27
+ while !queue. is_empty ( ) && max_cache[ * queue. back ( ) . unwrap ( ) ] < res {
28
+ queue. pop_back ( ) ;
29
+ }
30
+ queue. push_back ( i) ;
31
+ if * queue. front ( ) . unwrap ( ) > i + k as usize - 1 {
32
+ queue. pop_front ( ) ;
33
+ }
21
34
}
22
35
max_cache[ 0 ]
23
36
}
You can’t perform that action at this time.
0 commit comments