Minimum Moves to Equal Array Elements
Count the fewest moves, each adding 1 to all elements but one, that make every element of an array equal.
Given an integer array nums
Example 1
Output: 3
Explanation: [1, 2, 3] → [2, 3, 3] → [3, 4, 3] → [4, 4, 4].
Example 2
Output: 0
The Idea
Picture Example 1 as three stacks of blocks, 1, 2 and 3 blocks high. In one move you put a new block on every stack but one. The goal is stacks of equal height, and Example 1 gets there in three moves, each time leaving out a tallest stack.
But why leave out a tallest one, and could some other order finish in two moves? Every move makes most stacks taller, so the final height keeps climbing. Chasing that height is confusing. What stays easier to follow is how far each stack sticks out above the smallest one.
Whether the stacks are level depends only on those differences, not on the heights themselves. Adding a block to every stack but one changes the differences exactly as taking one block off the left-out stack would. So a move works like lowering a single element by 1.
The picture above plays out Example 1 move by move. The dashed teal line marks the level of the smallest element, and the orange blocks are the ones above it. At the start the gaps are 0, 1 and 2, so there are 3 orange blocks. Move 1 leaves out the 3. The other two stacks grow, the line rises with them, and the 3 now sticks out by one block instead of two. The orange count drops to 2, then to 1 after move 2, and to 0 after move 3.
Can one move ever remove two orange blocks? The stacks that get a block never fall closer to the line, so only the left-out stack can lose one. While the stacks are not level, leaving out a tallest stack always does lose one, because the smallest stacks get a block and lift the line. So the answer is the number of orange blocks: the sum of every element's gap above the smallest, 0 + 1 + 2 = 3 for Example 1.
Solution Approach
Three things are left to settle: whether to play the moves out or count them, how to add up the gaps, and how to keep the total exact for very large and very small numbers.
Playing the moves out
Why not simply make the moves, each time leaving out a tallest element, until all are equal? It gives the right answer, but it makes one move per orange block. For [0, 1000000]
Adding up the gaps
How do we get the orange count without making any move? Find the smallest element first, then add x - minx
Keeping the total exact
Can a gap be too big for the type that holds it? With Integer.MIN_VALUEInteger.MAX_VALUEintintxlonglong
Java Solution
The method minMoves
- First, find the smallest element. The variable
starts atmin , and a loop overInteger.MAX_VALUE lowers it withnums .Math.min - Next, a second loop adds each element's gap,
, to(long) x - min , amoves that starts at 0.long - Finally, return
, the number of orange blocks.moves
Beside it, a helper method named simulate
The main[1, 1, 5]Integer.MIN_VALUEInteger.MAX_VALUE
import java.util.Arrays;
public class MinimumMovesToEqualArrayElements {
public static long minMoves(int[] nums) {
int min = Integer.MAX_VALUE;
for (int x : nums) {
min = Math.min(min, x); // the smallest element
}
long moves = 0;
for (int x : nums) {
moves += (long) x - min; // this element's gap above the smallest
}
return moves;
}
// The slow way: really make the moves, always leaving out a largest element.
static long simulate(int[] input) {
int[] nums = input.clone();
long moves = 0;
while (true) {
int maxAt = 0;
boolean allEqual = true;
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[0]) allEqual = false;
if (nums[i] > nums[maxAt]) maxAt = i;
}
if (allEqual) return moves;
for (int i = 0; i < nums.length; i++) {
if (i != maxAt) nums[i]++;
}
moves++;
}
}
public static void main(String[] args) {
int[][] small = {{1, 2, 3}, {1, 1, 1}, {1, 1, 5}, {-3, 0, 2}, {7}};
for (int[] nums : small) {
System.out.println(Arrays.toString(nums) + " -> " + minMoves(nums)
+ " (simulated: " + simulate(nums) + ")");
}
int[] extremes = {Integer.MIN_VALUE, Integer.MAX_VALUE};
System.out.println(Arrays.toString(extremes) + " -> " + minMoves(extremes));
System.out.println("the same gap in int: " + (Integer.MAX_VALUE - Integer.MIN_VALUE));
}
}
Running it prints:
[1, 2, 3] -> 3 (simulated: 3)
[1, 1, 1] -> 0 (simulated: 0)
[1, 1, 5] -> 4 (simulated: 4)
[-3, 0, 2] -> 8 (simulated: 8)
[7] -> 0 (simulated: 0)
[-2147483648, 2147483647] -> 4294967295
the same gap in int: -1
On every small array the gap sum and the played-out moves agree. Example 1 gives 3 and Example 2 gives 0. For [1, 1, 5][-3, 0, 2]
Look at the last two lines. The two extremes need 4,294,967,295 moves, and the longintminMoves
Complexity
The method reads the array twice and keeps only two numbers.
- Time: O(n), because one loop finds the smallest of the n elements and a second loop adds each element's gap once.
- Space: O(1), because only
andmin are stored, and the array is read but never copied.moves
Turning a move into something simpler to count is the key here;