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 ; To store the closest sum ; Run three nested loops each loop for each element of triplet ; Update the closestSum ; Return the closest sum found ; Driver code
class GFG { public static int solution ( int arr [ ] , int x ) { int closestSum = Integer . MAX_VALUE ; for ( int i = 0 ; i < arr . length ; i ++ ) { for ( int j = i + 1 ; j < arr . length ; j ++ ) { for ( int k = j + 1 ; k < arr . length ; k ++ ) { if ( Math . abs ( x - closestSum ) > Math . abs ( x - ( arr [ i ] + arr [ j ] + arr [ k ] ) ) ) closestSum = ( arr [ i ] + arr [ j ] + arr [ k ] ) ; } } } return closestSum ; } public static void main ( String [ ] args ) { int arr [ ] = { - 1 , 2 , 1 , - 4 } ; int x = 1 ; System . out . print ( solution ( arr , x ) ) ; } }