Answers for "minimum increment / decrement to make array elements equal"

1

minimum increment / decrement to make array elements equal

public int solution(int[] A) {
        int N = A.length;
        int operations = 0;
        Arrays.sort(A);
        int mid = A[N/2];
        for(int i = 0; i < N; i++) {
            operations += Math.abs(A[i] - mid);
        }

        if(N % 2 == 0) {
            int temp = 0;
            mid = A[(N/2) - 1];

            for(int i = 0; i < N; i++) {
                temp += Math.abs(A[i] - mid);
            }
            operations = Math.min(operations, temp);
        }
        return operations;
    }
Posted by: Guest on October-24-2021

Code answers related to "minimum increment / decrement to make array elements equal"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language