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
#include <iostream> NEW_LINE #include <unordered_map> NEW_LINE using namespace std ; int countSum ( int a [ ] , int n , int sum ) { int i , j , k , 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 ] ; unordered_map < int , int > m ; for ( k = j + 1 ; k < n ; k ++ ) m [ a [ k ] ] ++ ; int twice_count = 0 ; for ( k = j + 1 ; k < n ; k ++ ) { twice_count += m [ req - a [ k ] ] ; if ( req - a [ k ] == a [ k ] ) twice_count -- ; } count += twice_count / 2 ; } } return count ; } int main ( ) { int arr [ ] = { 4 , 5 , 3 , 1 , 2 , 4 } ; int S = 13 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countSum ( arr , N , S ) ; return 0 ; }