Problem Description
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 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.
Key Insights
- Sort the array to easily locate the median.
- For a sorted array, the median is at index m = n // 2 (0-indexed).
- If k is greater than the current median, you must increase numbers starting from the median (and to its right) if they are less than k.
- If k is less than the current median, you must decrease numbers starting from the median (and to its left) if they are greater than k.
- Only numbers on the appropriate side of the median (including the median itself) need to be adjusted.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting. Space Complexity: O(1) or O(n) depending on the sorting algorithm in use.
Solution
The algorithm first sorts the array to determine the true median (using 0-indexing, the median is at index n // 2). Then, if k is greater than the median, iterate from the median to the end of the array and for any element less than k, add the difference (k - element) to the operations count. If k is less than the median, iterate from the median to the beginning of the array and for any element greater than k, add the difference (element - k) to the operations count. This greedy approach ensures the minimum number of operations since only the necessary adjustments are made directly on the elements that determine the median.