Leetcode 462 Solution

This article provides solution to leetcode question 462 (minimum-moves-to-equal-array-elements-ii)

https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii

Solution

class Solution {
public:
    int minMoves2(vector<int>& nums) {
        sort(nums.begin(), nums.end());

        int target = nums[(nums.size() - 1) / 2];

        int steps = 0;

        for (int i = 0; i < nums.size(); i++)
            steps += abs(nums[i] - target);

        return steps;
    }
};