Maximum of minimum difference of all pairs from subsequences of given size | Function to check a subsequence can be formed with min difference mid ; If a subsequence of size B with min diff = mid is possible return true else false ; Function to find the maximum of all minimum difference of pairs possible among the subsequence ; Sort the Array ; Stores the boundaries of the search space ; Store the answer ; Binary Search ; If subsequence can be formed with min diff mid and size B ; Right half ; Left half ; Driver code
function can_place ( A , n , B , mid ) { let count = 1 ; let last_position = A [ 0 ] ; for ( let i = 1 ; i < n ; i ++ ) { if ( A [ i ] - last_position >= mid ) { last_position = A [ i ] ; count ++ ; if ( count == B ) { return true ; } } } return false ; } function find_min_difference ( A , n , B ) { A . sort ( ) ; let s = 0 ; let e = A [ n - 1 ] - A [ 0 ] ; let ans = 0 ; while ( s <= e ) { let mid = parseInt ( ( s + e ) / 2 , 10 ) ; if ( can_place ( A , n , B , mid ) ) { ans = mid ; s = mid + 1 ; } else { e = mid - 1 ; } } return ans ; } let A = [ 1 , 2 , 3 , 5 ] ; let n = A . length ; let B = 3 ; let min_difference = find_min_difference ( A , n , B ) ; document . write ( min_difference ) ;