#C1216. Minimum Operations to Equalize Array Elements
Minimum Operations to Equalize Array Elements
Minimum Operations to Equalize Array Elements
You are given an array of N integers and an integer M. In one operation, you can increment or decrement all elements in a chosen contiguous subarray by 1. Your task is to determine the minimum number of operations required to make all the elements of the array equal. If it is impossible to do so, output -1.
It can be shown that if it is possible to equalize the array, the minimum number of operations required is given by the formula:
[ \text{operations} = \max(A) - \min(A), ]
where \( \max(A) \) and \( \min(A) \) are the maximum and minimum elements in the array, respectively. However, if M = 1 and the array is not already equal (i.e. \( \max(A) \neq \min(A) \)), then it is impossible and you should return -1.
Note: When M > 1, it is always possible to equalize the array.
inputFormat
The first line of input contains an integer T representing the number of test cases.
For each test case, the first line contains two integers N and M, where N is the number of elements in the array and M is the parameter described above. The second line contains N space-separated integers representing the array elements.
Input is read from standard input (stdin).
outputFormat
For each test case, output a single integer on a new line representing the minimum number of operations required to make all elements equal, or -1 if it is impossible.
Output is to be written to standard output (stdout).
## sample5
5 3
5 7 1 2 6
4 2
3 3 3 3
3 1
1 2 3
6 3
10 10 10 10 10 10
3 2
1 2 1
6
0
-1
0
1
</p>