Find a triplet in an array whose sum is closest to a given number | Function to return the sum of a triplet which is closest to x ; Sort the array ; To store the closest sum not using INT_MAX to avoid overflowing condition ; Fix the smallest number among the three integers ; Two pointers initially pointing at the last and the element next to the fixed element ; While there could be more pairs to check ; Calculate the sum of the current triplet ; If the sum is more closer than the current closest sum ; If sum is greater then x then decrement the second pointer to get a smaller sum ; Else increment the first pointer to get a larger sum ; Return the closest sum found ; Driver code
function solution ( arr , x ) { arr . sort ( ( a , b ) => a - b ) ; let closestSum = 1000000000 ; for ( let i = 0 ; i < arr . length - 2 ; i ++ ) { let ptr1 = i + 1 , ptr2 = arr . length - 1 ; while ( ptr1 < ptr2 ) { let sum = arr [ i ] + arr [ ptr1 ] + arr [ ptr2 ] ; if ( Math . abs ( 1 * x - sum ) < Math . abs ( 1 * x - closestSum ) ) { closestSum = sum ; } if ( sum > x ) { ptr2 -- ; } else { ptr1 ++ ; } } } return closestSum ; } let arr = [ - 1 , 2 , 1 , - 4 ] ; let x = 1 ; document . write ( solution ( arr , x ) ) ;