Check if end of a sorted Array can be reached by repeated jumps of one more , one less or same number of indices as previous jump | JavaScript program for the above approach ; Utility function to check if it is possible to move from index 1 to N - 1 ; Successfully reached end index ; memo [ i ] [ j ] is already calculated ; Check if there is any index having value of A [ i ] + j - 1 , A [ i ] + j or A [ i ] + j + 1 ; If A [ k ] > A [ i ] + j + 1 , can 't make a move further ; It 's possible to move A[k] ; Check is it possible to move from index k having previously taken A [ k ] - A [ i ] steps ; If yes then break the loop ; Store value of flag in memo ; Return memo [ i ] [ j ] ; Function to check if it is possible to move from index 1 to N - 1 ; Stores the memoized state ; Initialize all values as - 1 ; Initially , starting index = 1 ; Function call ; Driver code ; Function Call
let N = 8 ; function check ( memo , i , j , A ) { if ( i == N - 1 ) return 1 ; if ( memo [ i ] [ j ] != - 1 ) return memo [ i ] [ j ] ; let flag = 0 , k ; for ( k = i + 1 ; k < N ; k ++ ) { if ( A [ k ] - A [ i ] > j + 1 ) break ; if ( A [ k ] - A [ i ] >= j - 1 && A [ k ] - A [ i ] <= j + 1 ) flag = check ( memo , k , A [ k ] - A [ i ] , A ) ; if ( flag != 0 ) break ; } memo [ i ] [ j ] = flag ; return memo [ i ] [ j ] ; } function checkEndReach ( A , K ) { let memo = new Array ( N ) ; for ( var i = 0 ; i < memo . length ; i ++ ) { memo [ i ] = new Array ( 2 ) ; } for ( let i = 0 ; i < N ; i ++ ) { for ( let j = 0 ; j < N ; j ++ ) { memo [ i ] [ j ] = - 1 ; } } let startIndex = 1 ; if ( check ( memo , startIndex , K , A ) != 0 ) document . write ( " " ) ; else document . write ( " " ) ; } let A = [ 0 , 1 , 3 , 5 , 6 , 8 , 12 , 17 ] ; let K = 1 ; checkEndReach ( A , K ) ;