text: Sum of absolute differences of indices of occurrences of each array element | C ++ program for the above approach ; Function to find sum of differences of indices of occurrences of each unique array element ; Stores indices of each array element ; Store the indices ; Stores the sums ; Traverse the array ; Find sum for each element ; Iterate over the Map ; Calculate sum of occurrences of arr [ i ] ; Store sum for current element ; Print answer for each element ; Driver Code ; Given array ; Given size ; Function call
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void sum ( int arr [ ] , int n ) { map < int , vector < int > > mp ; for ( int i = 0 ; i < n ; i ++ ) { mp [ arr [ i ] ] . push_back ( i ) ; } int ans [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { int sum = 0 ; for ( auto it : mp [ arr [ i ] ] ) { sum += abs ( it - i ) ; } ans [ i ] = sum ; } for ( int i = 0 ; i < n ; i ++ ) { cout << ans [ i ] << " ▁ " ; } return ; } int main ( ) { int arr [ ] = { 1 , 3 , 1 , 1 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sum ( arr , n ) ; return 0 ; }