Smallest Difference Triplet from Three arrays | function to find maximum number ; function to find minimum number ; Finds and prints the smallest Difference Triplet ; sorting all the three arrays ; To store resultant three numbers ; pointers to arr1 , arr2 , arr3 respectively ; Loop until one array reaches to its end Find the smallest difference . ; maximum number ; Find minimum and increment its index . ; comparing new difference with the previous one and updating accordingly ; Print result ; Driver Code
< ? php function maximum ( $ a , $ b , $ c ) { return max ( max ( $ a , $ b ) , $ c ) ; } function minimum ( $ a , $ b , $ c ) { return min ( min ( $ a , $ b ) , $ c ) ; } function smallestDifferenceTriplet ( $ arr1 , $ arr2 , $ arr3 , $ n ) { sort ( $ arr1 ) ; sort ( $ arr2 ) ; sort ( $ arr3 ) ; $ res_min ; $ res_max ; $ res_mid ; $ i = 0 ; $ j = 0 ; $ k = 0 ; $ diff = PHP_INT_MAX ; while ( $ i < $ n && $ j < $ n && $ k < $ n ) { $ sum = $ arr1 [ $ i ] + $ arr2 [ $ j ] + $ arr3 [ $ k ] ; $ max = maximum ( $ arr1 [ $ i ] , $ arr2 [ $ j ] , $ arr3 [ $ k ] ) ; $ min = minimum ( $ arr1 [ $ i ] , $ arr2 [ $ j ] , $ arr3 [ $ k ] ) ; if ( $ min == $ arr1 [ $ i ] ) $ i ++ ; else if ( $ min == $ arr2 [ $ j ] ) $ j ++ ; else $ k ++ ; if ( $ diff > ( $ max - $ min ) ) { $ diff = $ max - $ min ; $ res_max = $ max ; $ res_mid = $ sum - ( $ max + $ min ) ; $ res_min = $ min ; } } echo $ res_max , " , ▁ " , $ res_mid , " , ▁ " , $ res_min ; } $ arr1 = array ( 5 , 2 , 8 ) ; $ arr2 = array ( 10 , 7 , 12 ) ; $ arr3 = array ( 9 , 14 , 6 ) ; $ n = sizeof ( $ arr1 ) ; smallestDifferenceTriplet ( $ arr1 , $ arr2 , $ arr3 , $ n ) ; ? >