Sum of squares of differences between all pairs of an array | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; 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 ; cout << ans ; } int main ( ) { int arr [ ] = { 2 , 8 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sumOfSquaredDifferences ( arr , N ) ; return 0 ; }