Minimum Operations to Make Array Equal

medium math arithmetic series

Problem

An integer n describes a hidden array arr of length n with arr[i] = 2·i + 1 — the first n odd numbers. In one operation you pick two indices x and y, subtract 1 from arr[x] and add 1 to arr[y]. Return the minimum number of operations needed to make every element of arr equal (1 ≤ n ≤ 10⁴; the answer fits in 32 bits).

Inputn = 6
Output9
arr = [1, 3, 5, 7, 9, 11] must all become the mean 6; the lower half is short by 5 + 3 + 1 = 9 units, and each unit is fixed by one paired operation.

def min_operations(n):
    # arr[i] = 2*i + 1, so the total sum is n*n and the mean is n
    target = n
    ops = 0
    for i in range(n // 2):
        ops += target - (2 * i + 1)   # gap below the mean
    # arithmetic series: ops == n*n // 4
    return ops
function minOperations(n) {
  // arr[i] = 2*i + 1, so the total sum is n*n and the mean is n
  const target = n;
  let ops = 0;
  for (let i = 0; i < Math.floor(n / 2); i++) {
    ops += target - (2 * i + 1); // gap below the mean
  }
  // arithmetic series: ops === Math.floor(n * n / 4)
  return ops;
}
int minOperations(int n) {
    // arr[i] = 2*i + 1, so the total sum is n*n and the mean is n
    int target = n;
    int ops = 0;
    for (int i = 0; i < n / 2; i++) {
        ops += target - (2 * i + 1); // gap below the mean
    }
    // arithmetic series: ops == n * n / 4
    return ops;
}
int minOperations(int n) {
    // arr[i] = 2*i + 1, so the total sum is n*n and the mean is n
    int target = n;
    int ops = 0;
    for (int i = 0; i < n / 2; i++) {
        ops += target - (2 * i + 1); // gap below the mean
    }
    // arithmetic series: ops == n * n / 4
    return ops;
}
Time: O(n) Space: O(1)