#K40217. Minimum Operations to Equalize Array Elements

    ID: 26594 Type: Default 1000ms 256MiB

Minimum Operations to Equalize Array Elements

Minimum Operations to Equalize Array Elements

Given an array of n integers and an integer k, determine the minimum number of operations required to make all array elements equal. In one operation, you can increment or decrement an element by 1. The goal is to check if it is possible to equalize all elements using at most k operations. If it is possible, output the minimum number of operations required; otherwise, output -1.

The number of operations needed to make all elements equal is computed as follows. Let \(a_1, a_2, \dots, a_n\) be the array. After sorting the array, choose the median \(m = a_{\lceil\frac{n}{2}\rceil}\) (using 0-indexing, \(m = arr[n//2]\)). Then the required number of operations is:

[ \sum_{i=1}^{n} |a_i - m| ]

If the sum above is less than or equal to k, then the answer is the sum; otherwise, it is not possible and you should output -1.

inputFormat

The first line contains two space-separated integers n and k where n (1 ≤ n ≤ 105) is the number of elements in the array and k (0 ≤ k ≤ 109) is the maximum number of allowed operations.

The second line contains n space-separated integers representing the array elements. Each element is between -109 and 109 inclusive.

outputFormat

Output a single integer which is the minimum number of operations needed to equalize the array elements if possible within k operations, or output -1 otherwise.

## sample
5 6
1 2 3 4 5
6