Minimum sum of absolute differences of pairs in a triplet from three arrays | Lower_bound function ; Function to find the value closest to K in the array A [ ] ; Initialize close value as the end element ; Find lower bound of the array ; If lower_bound is found ; If lower_bound is not the first array element ; If * ( it - 1 ) is closer to k ; Return closest value of k ; Function to find the minimum sum of abs ( arr [ i ] - brr [ j ] ) and abs ( brr [ j ] - crr [ k ] ) ; Sort the vectors arr and crr ; Initialize minimum as LET_MAX ; Traverse the array brr [ ] ; Stores the element closest to val from the array arr [ ] ; Stores the element closest to val from the array crr [ ] ; If sum of differences is minimum ; Update the minimum ; Print the minimum absolute difference possible ; Driver code ; Function Call
function lower_bound ( arr , key ) { let low = 0 ; let high = arr . length - 1 ; while ( low < high ) { let mid = low + Math . floor ( ( high - low ) / 2 ) ; if ( arr [ mid ] >= key ) { high = mid ; } else { low = mid + 1 ; } } return low ; } function closestValue ( A , k ) { let close = A [ A . length - 1 ] ; let it = lower_bound ( A , k ) ; if ( it != A . length ) { close = A [ it ] ; if ( it != 0 ) { if ( ( k - A [ it - 1 ] ) < ( close - k ) ) { close = A [ it - 1 ] ; } } } return close ; } function minPossible ( arr , brr , crr ) { arr . sort ( ) ; crr . sort ( ) ; let minimum = Number . MAX_VALUE ; for ( let val in brr ) { let arr_close = closestValue ( arr , val ) ; let crr_close = closestValue ( crr , val ) ; if ( Math . abs ( val - arr_close ) + Math . abs ( val - crr_close ) < minimum ) minimum = Math . abs ( val - arr_close ) + Math . abs ( val - crr_close ) ; } document . write ( minimum ) ; } let a = [ 1 , 8 , 5 ] ; let b = [ 2 , 9 ] ; let c = [ 5 , 4 ] ; minPossible ( a , b , c ) ;