Find a triplet in an array whose sum is closest to a given number | C # 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 ; 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
using System ; using System . Collections . Generic ; class GFG { static int solution ( List < int > arr , int x ) { arr . Sort ( ) ; int closestSum = int . MaxValue ; for ( int i = 0 ; i < arr . Count - 2 ; i ++ ) { int ptr1 = i + 1 , ptr2 = arr . Count - 1 ; while ( ptr1 < ptr2 ) { int sum = arr [ i ] + arr [ ptr1 ] + arr [ ptr2 ] ; if ( Math . Abs ( x - sum ) < Math . Abs ( x - closestSum ) ) { closestSum = sum ; } if ( sum > x ) { ptr2 -- ; } else { ptr1 ++ ; } } } return closestSum ; } public static void Main ( String [ ] args ) { int [ ] ar = { - 1 , 2 , 1 , - 4 } ; List < int > arr = new List < int > ( ar ) ; int x = 1 ; Console . WriteLine ( solution ( arr , x ) ) ; } }