#K55552. Minimum Operations to Equalize Energy Counters
Minimum Operations to Equalize Energy Counters
Minimum Operations to Equalize Energy Counters
You are given n energy counters representing the energy levels of n devices. In one operation, you can decrease the energy of a device that has more energy than the target value. The target value is defined as the average energy if the total energy is divisible evenly among all devices.
The task is to determine the minimum number of operations required to make every device's energy equal to the target value. If it is impossible to equalize the energy counters (i.e. the total energy is not divisible by n), you must output -1.
Note: In one operation, you can only remove one unit of energy from a device that has energy greater than the target value.
Mathematical Formulation:
Let \( E = \{e_1, e_2, \dots, e_n\} \) be the energy counters, and let the total energy be \( T = \sum_{i=1}^{n}e_i \). The operation is possible if and only if \( T \equiv 0 \; (\text{mod} \; n)\). The target energy is \( t = \frac{T}{n} \). The minimum number of operations needed is then given by \[ \text{operations} = \sum_{i=1}^{n} \max(0, e_i - t)\] if a solution exists, otherwise output -1.
inputFormat
The first line contains an integer n
(1 ≤ n ≤ 105), the number of energy counters.
The second line contains n
space-separated integers, representing the initial energy counts of each device. Each energy counter is a non-negative integer.
outputFormat
Output a single integer that is the minimum number of operations required to equalize all energy counters to the same value. If it is impossible, print -1
.
4
3 7 5 13
6