Find a triplet in an array whose sum is closest to a given number | C ++ implementation of the approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solution ( vector < int > & arr , int x ) { sort ( arr . begin ( ) , arr . end ( ) ) ; int closestSum = 1000000000 ; for ( int i = 0 ; i < arr . size ( ) - 2 ; i ++ ) { int ptr1 = i + 1 , ptr2 = arr . size ( ) - 1 ; while ( ptr1 < ptr2 ) { int sum = arr [ i ] + arr [ ptr1 ] + arr [ ptr2 ] ; if ( abs ( 1LL * x - sum ) < abs ( 1LL * x - closestSum ) ) { closestSum = sum ; } if ( sum > x ) { ptr2 -- ; } else { ptr1 ++ ; } } } return closestSum ; } int main ( ) { vector < int > arr = { -1 , 2 , 1 , -4 } ; int x = 1 ; cout << solution ( arr , x ) ; return 0 ; }