Find a triplet in an array whose sum is closest to a given number | Java implementation of the above approach ; Function to return the sum of a triplet which is closest to x ; Sort the array ; To store the closest sum Assigning long to avoid overflow condition when array has negative integers ; 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
import static java . lang . Math . abs ; import java . util . * ; class GFG { static int solution ( Vector < Integer > arr , int x ) { Collections . sort ( arr ) ; long closestSum = Integer . MAX_VALUE ; for ( int i = 0 ; i < arr . size ( ) - 2 ; i ++ ) { int ptr1 = i + 1 , ptr2 = arr . size ( ) - 1 ; while ( ptr1 < ptr2 ) { int sum = arr . get ( i ) + arr . get ( ptr1 ) + arr . get ( ptr2 ) ; if ( abs ( x - sum ) < abs ( x - closestSum ) ) { closestSum = sum ; } if ( sum > x ) { ptr2 -- ; } else { ptr1 ++ ; } } } return ( int ) closestSum ; } public static void main ( String [ ] args ) { Vector arr = new Vector ( Arrays . asList ( - 1 , 2 , 1 , - 4 ) ) ; int x = 1 ; System . out . println ( solution ( arr , x ) ) ; } }