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.
Example 1:
Input: nums = [1,2,3] Output: 3 Explanation: Only three moves are needed (remember each move increments two elements): [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
Example 2:
Input: nums = [1,1,1] Output: 0
Constraints:
n == nums.length1 <= nums.length <= 105-109 <= nums[i] <= 109The problem can be simplified by observing that incrementing n-1 elements is equivalent to decrementing 1 element. Thus, the number of moves required to make all elements in the array equal is equal to the total number of moves required to make all elements equal to the minimum element present in the array.
To achieve this, calculate the difference between each element and the minimum element, summing these differences yields the required number of moves.
This C solution keeps track of the minimum element and computes the sum of differences between each element and the minimum. This sum is the number of moves needed.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), Space Complexity: O(1)
Leetcode 462. Minimum Moves to Equal Array Elements II • Code with Alisha • 17,191 views views
Watch 9 more video solutions →Practice Minimum Moves to Equal Array Elements with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor