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 ; 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
using System ; using System . Collections ; using System . Collections . Generic ; class GFG { static int solution ( ArrayList arr , int x ) { int closestSum = int . MaxValue ; for ( int i = 0 ; i < arr . Count ; i ++ ) { for ( int j = i + 1 ; j < arr . Count ; j ++ ) { for ( int k = j + 1 ; k < arr . Count ; k ++ ) { if ( Math . Abs ( x - closestSum ) > Math . Abs ( x - ( ( int ) arr [ i ] + ( int ) arr [ j ] + ( int ) arr [ k ] ) ) ) { closestSum = ( ( int ) arr [ i ] + ( int ) arr [ j ] + ( int ) arr [ k ] ) ; } } } } return closestSum ; } public static void Main ( string [ ] args ) { ArrayList arr = new ArrayList ( ) { - 1 , 2 , 1 , - 4 } ; int x = 1 ; Console . Write ( solution ( arr , x ) ) ; } }