text: Count quadruples of given type from given array | Java program of the above approach ; lcount [ i ] [ j ] : Stores the count of i on left of index j ; rcount [ i ] [ j ] : Stores the count of i on right of index j ; Function to count unique elements on left and right of any index ; Find the maximum array element ; Calculate prefix sum of counts of each value ; Calculate suffix sum of counts of each value ; Function to count quadruples of the required type ; Driver Code
code: import java . util . * ; class GFG { static int maxN = 2002 ; static int [ ] [ ] lcount = new int [ maxN ] [ maxN ] ; static int [ ] [ ] rcount = new int [ maxN ] [ maxN ] ; static void fill_counts ( int a [ ] , int n ) { int i , j ; int maxA = a [ 0 ] ; for ( i = 0 ; i < n ; i ++ ) { if ( a [ i ] > maxA ) { maxA = a [ i ] ; } } for ( i = 0 ; i < n ; i ++ ) { lcount [ a [ i ] ] [ i ] = 1 ; rcount [ a [ i ] ] [ i ] = 1 ; } for ( i = 0 ; i <= maxA ; i ++ ) { for ( j = 1 ; j < n ; j ++ ) { lcount [ i ] [ j ] = lcount [ i ] [ j - 1 ] + lcount [ i ] [ j ] ; } for ( j = n - 2 ; j >= 0 ; j -- ) { rcount [ i ] [ j ] = rcount [ i ] [ j + 1 ] + rcount [ i ] [ j ] ; } } } static int countSubsequence ( int a [ ] , int n ) { int i , j ; fill_counts ( a , n ) ; int answer = 0 ; for ( i = 1 ; i < n ; i ++ ) { for ( j = i + 1 ; j < n - 1 ; j ++ ) { answer += lcount [ a [ j ] ] [ i - 1 ] * rcount [ a [ i ] ] [ j + 1 ] ; } } return answer ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 2 , 3 , 2 , 1 , 3 , 2 } ; System . out . print ( countSubsequence ( a , a . length ) ) ; } }