Count quadruplets with sum K from given array | Java 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
import java . util . * ; class GFG { static int countSum ( int a [ ] , int n , int sum ) { int i , j , k ; int count = 0 ; HashMap < Integer , Integer > m = new HashMap < > ( ) ; 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 . get ( sum - temp ) ; } for ( j = 0 ; j < i ; j ++ ) { int temp = a [ i ] + a [ j ] ; if ( temp < sum ) if ( m . containsKey ( temp ) ) m . put ( temp , m . get ( temp ) + 1 ) ; else m . put ( 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 ; System . out . print ( countSum ( arr , N , S ) ) ; } }