Holiday of Equality

Holiday of Equality
Codeforces easy

Given an array \(A\) of \(N\) integers, you may increase any element by \(1\) any number of times. Find the minimum total number of increments required to make all elements equal.

Solution

To equalize everyone with minimum increments, we need to raise all elements to the current maximum. To do this, we’ll write a functions that computes the maximum between two elements.

int max_function(int x, int y) {
    if (x > y) return x;
    else return y;
}

Now, we’ll compute the maximum element in the following way.

int n;
cin >> n;

int a[n];
for (int i = 0; i < n; i++) {
    cin >> a[i];
}

int max_value = a[0];
for (int i = 0; i < n; i++) {
    max_value = max_function(max_value, a[i]);
}

For each element \(i\), the amount to increment is \(max(A_1, \dots, A_n) - A_i\). Summing this value over all elemnts gives the minimum total amount of increments needed.

int coins = 0;
for (int i = 0; i < n; i++) {
    coins += max_value - a[i];
}

cout << coins;