Suppose we have a non-empty integer array, we have to find the minimum number of moves that are required to make all array elements equal, where a move is incrementing or decrementing a selected element by 1. So when the array is like [1, 2, 3], then the output will be 2, as 1 will be incremented to 2, and 3 will be decremented to 2.
To solve this, we will follow these steps −
Let us see the following implementation to get a better understanding −
class Solution: def minMoves2(self, nums): nums.sort() counter = 0 for i in nums: counter += abs(i-nums[len(nums)//2]) return counter ob1 = Solution() print(ob1.minMoves2([2,5,3,4]))