Sum of squares of differences between all pairs of an array | Java program for the above approach ; Function to calculate sum of squares of differences of all possible pairs ; Stores the final sum ; Stores temporary values ; Traverse the array ; Final sum ; Print the answer ; Driver Code ; Given array ; Size of the array ; Function call to find sum of square of differences of all possible pairs
class GFG { static void sumOfSquaredDifferences ( int arr [ ] , int N ) { int ans = 0 ; int sumA = 0 , sumB = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sumA += ( arr [ i ] * arr [ i ] ) ; sumB += arr [ i ] ; } sumA = N * sumA ; sumB = ( sumB * sumB ) ; ans = sumA - sumB ; System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 8 , 4 } ; int N = arr . length ; sumOfSquaredDifferences ( arr , N ) ; } }