Count quadruplets with sum K from given array | C # program for the above approach ; Function to return the number of quadruplets having the given sum ; Initialize variables ; Initialize answer ; Store the frequency of sum of first two elements ; Traverse from 0 to N - 1 , where arr [ i ] is the 3 rd element ; All possible 4 th elements ; Sum of last two element ; Frequency of sum of first two elements ; Store frequency of all possible sums of first two elements ; Return the answer ; Driver Code ; Given array [ ] arr ; Given sum S ; Function Call
using System ; using System . Collections . Generic ; class GFG { static int countSum ( int [ ] a , int n , int sum ) { int i , j ; int count = 0 ; Dictionary < int , int > m = new Dictionary < int , int > ( ) ; for ( i = 0 ; i < n - 1 ; i ++ ) { for ( j = i + 1 ; j < n ; j ++ ) { int temp = a [ i ] + a [ j ] ; if ( temp < sum && m . ContainsKey ( sum - temp ) ) count += m [ sum - temp ] ; } for ( j = 0 ; j < i ; j ++ ) { int temp = a [ i ] + a [ j ] ; if ( temp < sum ) if ( m . ContainsKey ( temp ) ) m [ temp ] ++ ; else m . Add ( temp , 1 ) ; } } return count ; } public static void Main ( String [ ] args ) { int [ ] arr = { 4 , 5 , 3 , 1 , 2 , 4 } ; int S = 13 ; int N = arr . Length ; Console . Write ( countSum ( arr , N , S ) ) ; } }