Find the minimum of maximum length of a jump required to reach the last island in exactly k jumps | Function that returns true if it is possible to reach end of the array in exactly k jumps ; Variable to store the number of steps required to reach the end ; If it is possible to reach the end in exactly k jumps ; Returns the minimum maximum distance required to reach the end of the array in exactly k jumps ; Stores the answer ; Binary search to calculate the result ; Driver Code
function isPossible ( arr , n , dist , k ) { let req = 0 ; let curr = 0 ; let prev = 0 ; for ( let i = 0 ; i < n ; i ++ ) { while ( curr != n && arr [ curr ] - arr [ prev ] <= dist ) { curr ++ ; } req ++ ; if ( curr == n ) { break ; } prev = curr - 1 ; } if ( curr != n ) { return false ; } if ( req <= k ) { return true ; } return false ; } function minDistance ( arr , n , k ) { let l = 0 ; let h = arr [ n - 1 ] ; let ans = 0 ; while ( l <= h ) { let m = Math . floor ( ( l + h ) / 2 ) ; if ( isPossible ( arr , n , m , k ) ) { ans = m ; h = m - 1 ; } else { l = m + 1 ; } } return ans ; } let arr = [ 2 , 15 , 36 , 43 ] ; let n = arr . length ; let k = 2 ; document . write ( minDistance ( arr , n , k ) ) ;