[LeetCode] Minimum Operations to Make Median of Array Equal to K

3107. Minimum Operations to Make Median of Array Equal to K

You are given an integer array nums and a non-negative integer k. In one operation, you can increase or decrease any element by 1.

Return the minimum number of operations needed to make the median of nums equal to k.

The median of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the larger of the two values is taken.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
long long minOperationsToMakeMedianK(vector<int>& A, int k) {
sort(begin(A), end(A));
int n = A.size();
int l2 = A.size() / 2;
long long res = 0;
for(int i = 0; i < l2; i++) {
if(A[i] > k) {
res += A[i] - k;
A[i] = k;
}
}
for(int i = l2 + 1; i < A.size(); i++) {
if(A[i] < k) {
res += k - A[i];
A[i] = k;
}
}

return res + abs(k - A[l2]);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/04/09/PS/LeetCode/minimum-operations-to-make-median-of-array-equal-to-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.