Minimum Moves to Equal Array Elements

Medium · Math · Array · Math

Problem

You are given an integer array nums of length n. In one move you choose n - 1 of the elements and increase each of them by 1.

Return the fewest moves needed to make all the elements equal. The answer fits in a 32-bit integer.

Examples

Input: nums = [2,5,3]
Output: 4

Relative to the minimum 2, the others are 3 and 1 above it: 3 + 1 = 4 moves.

Input: nums = [6,6,6,6]
Output: 0

Nothing to do.

Input: nums = [-1,4]
Output: 5

Each move raises -1 by one relative to 4, and they are 5 apart.

Constraints

Approaches

Follow-up

If a move may instead add or subtract 1 on a single element, the best common value is the median, and the answer is the sum of distances to it. Different move, different target: here the minimum, there the median.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…