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
< ? php function sumOfMinAbsDifferences ( $ arr , $ n ) { sort ( $ arr ) ; sort ( $ arr , $ n ) ; $ sum = 0 ; $ sum += abs ( $ arr [ 0 ] - $ arr [ 1 ] ) ; $ sum += abs ( $ arr [ $ n - 1 ] - $ arr [ $ n - 2 ] ) ; for ( $ i = 1 ; $ i < $ n - 1 ; $ i ++ ) $ sum += min ( abs ( $ arr [ $ i ] - $ arr [ $ i - 1 ] ) , abs ( $ arr [ $ i ] - $ arr [ $ i + 1 ] ) ) ; return $ sum ; } $ arr = array ( 5 , 10 , 1 , 4 , 8 , 7 ) ; $ n = sizeof ( $ arr ) ; echo " Sum = " ? >