[LeetCode] Minimum Moves to Equal Array Elements II

462. Minimum Moves to Equal Array Elements II

Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.

In one move, you can increment or decrement an element of the array by 1.

Test cases are designed so that the answer will fit in a 32-bit integer.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int minMoves2(vector<int>& A) {
sort(begin(A), end(A));
int n = A.size(), m = A[n/2];
int res = 0;
for(auto& a : A)
res += abs(m-a);
return res;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
long long helper(vector<int>& A, int k) {
long long res = 0;
for(auto& a : A) {
res += abs(k - a);
}
return res;
}
public:
int minMoves2(vector<int>& A) {
long long res = LLONG_MAX, ma = *max_element(begin(A), end(A)), mi = *min_element(begin(A), end(A));
while(mi <= ma) {
int m = mi + (ma - mi) / 2;
long long diff = helper(A, m);
long long diff2 = helper(A, m + 1);
if(diff < diff2) ma = m - 1;
else mi = m + 1;
res = min({res, diff, diff2});
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/30/PS/LeetCode/minimum-moves-to-equal-array-elements-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.