KatInterview

Minimum Operations to Equalize Array by Selective Increments

Arrays & HashingAuto-graded · 22 test cases
MediumAuto-gradedArrays & Hashingmatharraysgreedy

Last updated

Tests insight that incrementing all-but-one is equivalent to decrementing one, leading to a sum-based formula instead of simulation.

You have an integer array. In a single operation, you select exactly one index and increment every element except the one at that index by 1. Determine the minimum number of operations required to make all array elements equal.

Rules

  • One operation increments all elements except a single chosen element.
  • Different operations may skip different elements.
  • If all elements are already equal, the answer is 0.

Constraints

  • 1 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • The result may exceed 2^31 but remains below 2^53.

Examples

Example 1

Input: min_ops_equalize([1, 3])

Output: 2

Example 2

Input: min_ops_equalize([4, 1, 6])

Output: 8

Example 3

Input: min_ops_equalize([-2, 5, -2, 0])

Output: 9

Hints

Hint 1

Think about what happens to the *differences* between elements when you increment all but one.

Hint 2

Incrementing everything except index i has the same effect on relative values as decrementing nums[i] alone.

Hint 3

Since we can only effectively lower values (via the decrement view), what is the best common target?