Minimum Increment / decrement to make array elements equal | Java program to find minimum Increment or decrement to make array elements equal ; Function to return minimum operations need to be make each element of array equal ; Initialize cost to 0 ; Sort the array ; Middle element ; Find Cost ; If n , is even . Take minimum of the Cost obtained by considering both middle elements ; Find cost again ; Take minimum of two cost ; Return total cost ; Driver Code
import java . util . * ; class GfG { static int minCost ( int A [ ] , int n ) { int cost = 0 ; Arrays . sort ( A ) ; int K = A [ n / 2 ] ; for ( int i = 0 ; i < n ; ++ i ) cost += Math . abs ( A [ i ] - K ) ; if ( n % 2 == 0 ) { int tempCost = 0 ; K = A [ ( n / 2 ) - 1 ] ; for ( int i = 0 ; i < n ; ++ i ) tempCost += Math . abs ( A [ i ] - K ) ; cost = Math . min ( cost , tempCost ) ; } return cost ; } public static void main ( String [ ] args ) { int A [ ] = { 1 , 6 , 7 , 10 } ; int n = A . length ; System . out . println ( minCost ( A , n ) ) ; } }