Minimum sum of absolute differences of pairs in a triplet from three arrays | Java program for the above approach ; 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 INT_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
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { public static int lower_bound ( int arr [ ] , int key ) { int low = 0 ; int high = arr . length - 1 ; while ( low < high ) { int mid = low + ( high - low ) / 2 ; if ( arr [ mid ] >= key ) { high = mid ; } else { low = mid + 1 ; } } return low ; } static int closestValue ( int A [ ] , int k ) { int close = A [ A . length - 1 ] ; int 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 ; } static void minPossible ( int arr [ ] , int brr [ ] , int crr [ ] ) { Arrays . sort ( arr ) ; Arrays . sort ( crr ) ; int minimum = Integer . MAX_VALUE ; for ( int val : brr ) { int arr_close = closestValue ( arr , val ) ; int 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 ) ; } System . out . println ( minimum ) ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 8 , 5 } ; int b [ ] = { 2 , 9 } ; int c [ ] = { 5 , 4 } ; minPossible ( a , b , c ) ; } }