Minimum Moves to Equal Array Elements II

Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1.

Example:

Input:
[1,2,3]

Output:
2

Explanation:
Only two moves are needed (remember each move increments or decrements one element):

[1,2,3]  =>  [2,2,3]  =>  [2,2,2]

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

int minMoves2(vector<int&nums)
{
    sort(nums.begin(), nums.end());
    int n = nums.size();
    int len = n / 2;
    int ans = 0;
    for (int i = 0i < ni++)
    {
        ans += abs(nums[i] - nums[len]);
    }
    return ans;
}

int main()
{
    vector<intnums = {123};

    cout << minMoves2(nums);

    return 0;
}


No comments:

Post a Comment