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: using System ; using System . Collections . Generic ; class GFG { static void sum ( int [ ] arr , int n ) { Dictionary < int , List < int > > mp = new Dictionary < int , List < int > > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { List < int > v = new List < int > ( ) ; v . Add ( i ) ; if ( mp . ContainsKey ( arr [ i ] ) ) v . AddRange ( mp [ arr [ i ] ] ) ; mp [ arr [ i ] ] = v ; } int [ ] ans = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { int sum = 0 ; foreach ( int it in mp [ arr [ i ] ] ) { sum += Math . Abs ( it - i ) ; } ans [ i ] = sum ; } for ( int i = 0 ; i < n ; i ++ ) { Console . Write ( ans [ i ] + " ▁ " ) ; } return ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 3 , 1 , 1 , 2 } ; int n = arr . Length ; sum ( arr , n ) ; } }