Count quadruplets with sum K from given array | C # program for the above approach ; Function to return the number of quadruplets having given sum ; Initialize variables ; Initialize answer ; All possible first elements ; All possible second element ; Use map to find the fourth element ; All possible third elements ; Calculate number of valid 4 th elements ; Update the twice_count ; Unordered pairs ; Return 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 , k ; int l ; int count = 0 ; for ( i = 0 ; i < n - 3 ; i ++ ) { for ( j = i + 1 ; j < n - 2 ; j ++ ) { int req = sum - a [ i ] - a [ j ] ; Dictionary < int , int > m = new Dictionary < int , int > ( ) ; for ( k = j + 1 ; k < n ; k ++ ) if ( m . ContainsKey ( a [ k ] ) ) { m [ a [ k ] ] ++ ; } else { m . Add ( a [ k ] , 1 ) ; } int twice_count = 0 ; for ( k = j + 1 ; k < n ; k ++ ) { if ( m . ContainsKey ( req - a [ k ] ) ) twice_count += m [ req - a [ k ] ] ; if ( req - a [ k ] == a [ k ] ) twice_count -- ; } count += twice_count / 2 ; } } 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 ) ) ; } }