Sum of absolute differences of indices of occurrences of each array element | Java 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
import java . util . * ; class GFG { static void sum ( int arr [ ] , int n ) { HashMap < Integer , Vector < Integer > > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { Vector < Integer > v = new Vector < > ( ) ; v . add ( i ) ; if ( mp . containsKey ( arr [ i ] ) ) v . addAll ( mp . get ( arr [ i ] ) ) ; mp . put ( arr [ i ] , v ) ; } int [ ] ans = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { int sum = 0 ; for ( int it : mp . get ( arr [ i ] ) ) { sum += Math . abs ( it - i ) ; } ans [ i ] = sum ; } for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( ans [ i ] + " ▁ " ) ; } return ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 1 , 1 , 2 } ; int n = arr . length ; sum ( arr , n ) ; } }