File tree 1 file changed +10
-9
lines changed
scripts/algorithms/J/Jump Game V
1 file changed +10
-9
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 183 ms (Top 40.91%) | Memory: 47.7 MB (Top 22.73%)
1
2
var maxJumps = function ( arr , d ) {
2
-
3
+
3
4
let n = arr . length ;
4
5
let dp = new Array ( n ) . fill ( 0 ) ;
5
6
let result = 0 ;
6
-
7
+
7
8
// Time complexity:
8
9
// O(nlogn) + O(n*d) => O(ologn)
9
-
10
+
10
11
// First we sort the arr (small -> large) , then calculating DP by sortedArr.
11
12
// O(nlogn)
12
13
let sortedArr = arr . map ( ( v , i ) => ( [ v , i ] ) ) . sort ( ( a , b ) => a [ 0 ] - b [ 0 ] ) ;
13
-
14
+
14
15
// Shifting with single way
15
16
// mid -> left ; mid -> right
16
17
// O(n*d)
17
18
for ( let index = 1 ; index < n ; index ++ ) {
18
19
let [ v , i ] = sortedArr [ index ] ;
19
-
20
+
20
21
for ( let shift = 1 ; shift <= d ; shift ++ ) {
21
22
if ( i + shift >= n || arr [ i + shift ] >= arr [ i ] ) break ;
22
23
dp [ i ] = Math . max ( dp [ i ] , dp [ i + shift ] + 1 ) ;
23
24
if ( dp [ i ] > result ) result = dp [ i ] ;
24
25
} ;
25
-
26
+
26
27
for ( let shift = - 1 ; shift >= - d ; shift -- ) {
27
28
if ( i + shift < 0 || arr [ i + shift ] >= arr [ i ] ) break ;
28
29
dp [ i ] = Math . max ( dp [ i ] , dp [ i + shift ] + 1 ) ;
29
30
if ( dp [ i ] > result ) result = dp [ i ] ;
30
31
} ;
31
32
} ;
32
-
33
+
33
34
return result + 1 ;
34
-
35
- } ;
35
+
36
+ } ;
You can’t perform that action at this time.
0 commit comments