#3736
Minimum Moves to Equal Array Elements III
EasyArrayMathHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
To minimize moves, all elements should be raised to the maximum value in the array, as this requires the least total increase.
⚙️
Algorithm
3 steps- 1Step 1: Find the maximum value in the array.
- 2Step 2: Calculate the total moves needed by summing the differences between the maximum and each element.
- 3Step 3: Return the total moves.
solution.py3 lines
1def minMoves(nums):
2 max_val = max(nums)
3 return sum(max_val - num for num in nums)ℹ
Complexity note: We only traverse the array twice: once to find the max and once to calculate moves.
- 1All elements should reach the maximum value to minimize moves.
- 2The number of moves is simply the sum of differences from the maximum.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.