You are given a list of whole numbers, nums, of length n. In one move you pick n − 1 of the numbers, every number except one, and add 1 to each of them.
Return the smallest number of moves that makes all the numbers equal.
Example 1
Input: nums = [3, 7, 4] Output: 5 Why: the 7 sits 4 above the minimum and the 4 sits 1 above
2 more examples and the constraints
Example 2
Input: nums = [5, 5, 5, 5] Output: 0 Why: they are already equal
Example 3
Input: nums = [-2, 6] Output: 8 Why: raise the −2 eight times while the 6 sits out
Constraints
- 1 ≤ n ≤ 100,000
- −1,000,000,000 ≤ nums[i] ≤ 1,000,000,000
- The answer fits in a 32-bit signed integer
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Simulate in roundsO(n²)
- Distance to the minimumO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 numbers | Verdict |
|---|---|---|---|
| Simulate in rounds | O(n²) | Shows the idea; too slow | |
| Distance to the minimum | O(n) | Best; two quick passes |
n = how many numbers are in the list.
Edge cases to test
- One number. [42] needs 0 moves: it already equals itself.
- Already equal. [5, 5, 5, 5] gives 0.
- Negative numbers. [-5, -1, -3]: the gaps to −5 are 0, 4 and 2, so 6.
- Huge gap. [-1,000,000,000, 1,000,000,000] needs 2,000,000,000 moves, which overflows a 32-bit sum on the way.
- Several copies of the largest. [1, 9, 9] gives 16: each 9 is 8 above the minimum.
Common mistakes
- Counting the distance to the maximum instead of the minimum: raising everyone is the same as lowering one.
- Summing the gaps in a 32-bit int, which overflows when one gap is near 2 billion.
- Simulating one move at a time, which can need billions of moves.
How to talk through it
- 1Clarify. Can the numbers be negative? Does the answer fit in 32 bits? Is a move always exactly n − 1 numbers?
- 2Give the brute force. Simulate rounds: raise all but the largest by the gap. It works but costs O(n²).
- 3Flip the move. Raising everyone but x is, relative to the rest, lowering x by 1. So count decrements.
- 4Code the sum. Find the minimum, add up x − min for every x in a 64-bit total.
- 5Test out loud. Run a single number, an all-equal list and the ±1,000,000,000 pair before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?