
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum Moves to Equal Array Elements II in Python
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 −
- sort the array nums
- set counter as 0
- for i in nums, do
- counter := counter + absolute of (i – nums[length of nums / 2])
- return counter
Example(Python)
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]))
Input
[2,5,3,4]
Output
4
Advertisements