Sum of minimum absolute difference of each array element | java implementation to find the sum of minimum absolute difference of each array element ; function to find the sum of minimum absolute difference ; sort the given array ; initialize sum ; min absolute difference for the 1 st array element ; min absolute difference for the last array element ; find min absolute difference for rest of the array elements and add them to sum ; required sum ; Driver code
import java . * ; import java . util . Arrays ; public class GFG { static int sumOfMinAbsDifferences ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int sum = 0 ; sum += Math . abs ( arr [ 0 ] - arr [ 1 ] ) ; sum += Math . abs ( arr [ n - 1 ] - arr [ n - 2 ] ) ; for ( int i = 1 ; i < n - 1 ; i ++ ) sum += Math . min ( Math . abs ( arr [ i ] - arr [ i - 1 ] ) , Math . abs ( arr [ i ] - arr [ i + 1 ] ) ) ; return sum ; } public static void main ( String args [ ] ) { int arr [ ] = { 5 , 10 , 1 , 4 , 8 , 7 } ; int n = arr . length ; System . out . println ( " Sum ▁ = ▁ " + sumOfMinAbsDifferences ( arr , n ) ) ; } }