Check if it is possible to reach M from 0 by given paths | Function to check if it is possible to reach M from 0 ; Stores the farther point that can reach from 1 point ; Stores the farthest point it can go for each index i ; Initialize rightMost [ i ] with 0 ; Traverse the array ; Update the rightMost position reached from a1 ; Find the farthest point it can reach from i ; If point < can be reached ; Driver Code
function canReach0toM ( a , n , m ) { let rightMost = new Array ( m + 1 ) ; let dp = new Array ( m + 1 ) ; for ( let i = 0 ; i <= m ; i ++ ) { rightMost [ i ] = 0 ; } for ( let i = 0 ; i < n ; i ++ ) { let a1 = a [ i ] [ 0 ] ; let b1 = a [ i ] [ 1 ] ; rightMost [ a1 ] = Math . max ( rightMost [ a1 ] , b1 ) ; } for ( let i = m ; i >= 0 ; i -- ) { dp [ i ] = i ; for ( let j = Math . min ( m , rightMost [ i ] ) ; j > i ; j -- ) { dp [ i ] = Math . max ( dp [ i ] , dp [ j ] ) ; } } if ( dp [ 0 ] >= m ) { document . write ( " " ) ; } else { document . write ( " " ) ; } } let arr = [ [ 0 , 2 ] , [ 2 , 2 ] , [ 2 , 5 ] , [ 4 , 5 ] ] ; let M = 5 ; let N = arr . length ; canReach0toM ( arr , N , M ) ;