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
#include <iostream> NEW_LINE #include <unordered_map> NEW_LINE using namespace std ; int countSum ( int a [ ] , int n , int sum ) { int i , j , k ; int count = 0 ; unordered_map < int , int > m ; for ( i = 0 ; i < n - 1 ; i ++ ) { for ( j = i + 1 ; j < n ; j ++ ) { int temp = a [ i ] + a [ j ] ; if ( temp < sum ) count += m [ sum - temp ] ; } for ( j = 0 ; j < i ; j ++ ) { int temp = a [ i ] + a [ j ] ; if ( temp < sum ) m [ temp ] ++ ; } } 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 ; }