Given a sorted array and a number x , find the pair in array whose sum is closest to x | Prints the pair with sum closest to x ; To store indexes of result pair ; Initialize left and right indexes and difference between pair sum and x ; While there are elements between l and r ; Check if this pair is closer than the closest pair so far ; If this pair has more sum , move to smaller values . ; Move to larger values ; Driver Code
< ? php function printClosest ( $ arr , $ n , $ x ) { $ res_l ; $ res_r ; $ l = 0 ; $ r = $ n - 1 ; $ diff = PHP_INT_MAX ; while ( $ r > $ l ) { if ( abs ( $ arr [ $ l ] + $ arr [ $ r ] - $ x ) < $ diff ) { $ res_l = $ l ; $ res_r = $ r ; $ diff = abs ( $ arr [ $ l ] + $ arr [ $ r ] - $ x ) ; } if ( $ arr [ $ l ] + $ arr [ $ r ] > $ x ) $ r -- ; else $ l ++ ; } echo " ▁ The ▁ closest ▁ pair ▁ is ▁ " , $ arr [ $ res_l ] , " ▁ and ▁ " , $ arr [ $ res_r ] ; } $ arr = array ( 10 , 22 , 28 , 29 , 30 , 40 ) ; $ x = 54 ; $ n = count ( $ arr ) ; printClosest ( $ arr , $ n , $ x ) ; ? >