Array formed using sum of absolute differences of that element with all other elements | C ++ program for the above approach ; Function to return the new array ; Initialize the Arraylist ; Sum of absolute differences of element with all elements ; Initialize int sum to 0 ; Add the value of sum to ans ; Return the final ans ; Driver Code ; Given array arr [ ] ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > calculate ( int * arr , int n ) { vector < int > ans ; for ( int i = 0 ; i < n ; i ++ ) { int sum = 0 ; for ( int j = 0 ; j < n ; j ++ ) { sum += abs ( arr [ i ] - arr [ j ] ) ; } ans . push_back ( sum ) ; } return ans ; } int main ( ) { int arr [ ] = { 2 , 3 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; vector < int > ans = calculate ( arr , n ) ; cout << " [ " ; for ( auto itr : ans ) cout << itr << " , ▁ " ; cout << " ] " ; return 0 ; }