#K68372. Equalize Array Elements with Fixed Increment Operations

    ID: 32850 Type: Default 1000ms 256MiB

Equalize Array Elements with Fixed Increment Operations

Equalize Array Elements with Fixed Increment Operations

You are given an array of n integers and an integer d. In one operation, you can add or subtract d from any element of the array. The task is to determine the minimum number of operations required to make all elements of the array equal. If it is impossible to equalize the array using such operations, output -1.

A necessary and sufficient condition for equalization is that all array elements have the same remainder when divided by d. If this condition holds, one optimal approach is to choose the median of the array and compute the number of operations needed as follows:

[ \text{operations} = \sum_{i=1}^{n} \frac{|a_i - m|}{d} ]

where m is the median of the array after sorting.

Examples:

  • Input: n = 3, d = 2, arr = [2, 4, 6] → Output: 2
  • Input: n = 4, d = 3, arr = [1, 2, 3, 4] → Output: -1

inputFormat

The input is read from the standard input with the following format:

n d
a1 a2 a3 ... an

Here, n is the number of elements in the array, d is the fixed increment/decrement value, and a1, a2, ..., an represent the array elements.

outputFormat

Output a single integer which is the minimum number of operations needed to make all the elements equal. If it is not possible, output -1.

## sample
3 2
2 4 6
2