Problem
Given an integer array nums
of size n
, return the minimum number of moves required to make all array elements equal.
In one move, you can increment n - 1
elements of the array by 1
.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Maths
To make all elements equal by incrementing n-1
elements by 1
in each move, we can observe the following:
- Instead of incrementing
n-1
elements, an equivalent problem is to decrement one element by1
. - We need to make all elements equal to the minimum element in the array.
- The number of moves required is the sum of all elements minus the product of the minimum element and the size of the array.
And the mathematical formula will be:
- The total number of moves required:
sum(nums) - n * min(nums)
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(1)