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 of length n, one move adds 1 to n - 1 of its elements, that is, to every element except one. Return the smallest number of moves that makes all the elements equal.

Example 1
Input: nums = [1, 2, 3]
Output: 3
Explanation: [1, 2, 3] → [2, 3, 3] → [3, 4, 3] → [4, 4, 4].
Example 2
Input: nums = [1, 1, 1]
Output: 0
Solution

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 array 1, 2, 3 drawn as stacks of blocks through three moves. Blocks above the dashed teal line, the level of the smallest element, are orange: 3 at the start, then 2, 1 and 0, so each move removes one orange block.

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] that is a million moves, and each move scans the whole array to find a tallest element and add the blocks.

Adding up the gaps

How do we get the orange count without making any move? Find the smallest element first, then add x - min for every element x. That takes two passes over the array. The same total can also be written as the sum of the array minus n times the smallest element.

Keeping the total exact

Can a gap be too big for the type that holds it? With Integer.MIN_VALUE, -2,147,483,648, and Integer.MAX_VALUE, 2,147,483,647, in one array, the gap between them is 4,294,967,295. A 32-bit int cannot hold that, and the subtraction done in int wraps around to a wrong number. Casting x to long before subtracting makes Java subtract in 64 bits, and the running total is a long too, which is also what the method returns.

Java Solution

The method minMoves works in these steps:

  1. First, find the smallest element. The variable min starts at Integer.MAX_VALUE, and a loop over nums lowers it with Math.min.
  2. Next, a second loop adds each element's gap, (long) x - min, to moves, a long that starts at 0.
  3. Finally, return moves, the number of orange blocks.

Beside it, a helper method named simulate plays the moves out the slow way, on a copy of the array, always leaving out a largest element. It is there only so the program can check the two answers against each other.

The main method runs both examples, [1, 1, 5], an array with negative numbers and a single element, each next to its simulated count. Then it tries Integer.MIN_VALUE and Integer.MAX_VALUE together in one array.

Java
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:

Output
[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] the 5 sticks out by 4, so 4 moves, each leaving out the 5. In [-3, 0, 2] the smallest is -3, the gaps are 0, 3 and 5, and the total is 8. The single element 7 is already equal to itself, so it needs no move.

Look at the last two lines. The two extremes need 4,294,967,295 moves, and the long total holds that number exactly. The same subtraction in int prints -1, and a version of minMoves without the cast returns that same -1 for this array.

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 min and moves are stored, and the array is read but never copied.

Turning a move into something simpler to count is the key here; Bulb Switcher also gets its answer from a change of view.