Array element with minimum sum of absolute differences | Java implementation of the approach ; Function to return the minimized sum ; Sort the array ; Median of the array ; Calculate the minimized sum ; Return the required sum ; Driver code
import java . util . * ; class GFG { static int minSum ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int x = arr [ ( int ) n / 2 ] ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += Math . abs ( arr [ i ] - x ) ; return sum ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 3 , 9 , 3 , 6 } ; int n = arr . length ; System . out . println ( minSum ( arr , n ) ) ; } }