#C8053. Minimum Operations to Equal Array Elements
Minimum Operations to Equal Array Elements
Minimum Operations to Equal Array Elements
You are given an array of m integers. Your task is to compute the minimum number of operations needed to make all elements of the array equal. In each operation, you may increase or decrease any element by 1.
The optimal strategy is to use the median of the array as the target value. If the array is sorted, the median is the middle element (for 0-indexed arrays, it is at index m / 2
when m
is odd, and any value between the two middle elements when m
is even will yield the minimum number of operations). The total number of operations is the sum of the absolute differences between each element and the median.
If the input array already has all elements equal, the output should be 0
.
Note: It is always possible to equalize the elements using the allowed operations.
inputFormat
The first line contains an integer m indicating the number of elements in the array. The second line contains m space-separated integers representing the array elements.
outputFormat
Output a single integer representing the minimum number of operations required to make all array elements equal.
## sample5
3 3 3 3 5
2
</p>