Skip to main content

Minimum Moves to Equal Array Elements

MediumArrayGreedyMath

Description

Given an integer array nums of size n, return the minimum number of moves required to make all elements equal. A move increments n-1 elements by 1.

Examples

Input:nums = [1,2,3]
Output:3
Explanation:

[1,2,3]->[2,3,3]->[3,4,3]->[4,4,4].

Input:nums = [1,1,1]
Output:0
Explanation:

All elements are already equal, so no moves are needed.

Input:nums = [5,6,10,11]
Output:12
Explanation:

Each move increments n-1 elements by 1, equivalent to decrementing one element by 1. The minimum moves equal the sum of differences from the minimum: (5-5)+(6-5)+(10-5)+(11-5) = 0+1+5+6 = 12. But with 4 elements and n-1=3 incremented per move, 10 moves are needed.

Constraints

  • 1 ≤ n ≤ 10⁵

Ready to solve this problem?

Practice solo and sharpen your skills for technical interviews.