Minimum Operations to Make Median of Array Equal to K - Problem
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 when the array is sorted in non-decreasing order. If there are two choices for a median, the larger of the two values is taken.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [2,1,3,4], k = 2
›
Output:
1
💡 Note:
Sort array to [1,2,3,4]. Median is at index 2 with value 3. Need |3-2|=1 operation to make median 2. All elements satisfy constraints: 1,2 ≤ 2 and 4 ≥ 2. Total: 1 operation.
Example 2 — Already Optimal
$
Input:
nums = [1,2,3], k = 2
›
Output:
0
💡 Note:
Sort array to [1,2,3]. Median is 2 which equals k. All elements satisfy median property: 1 ≤ 2 and 3 ≥ 2. No operations needed.
Example 3 — Large Adjustment
$
Input:
nums = [1,5,6], k = 3
›
Output:
2
💡 Note:
Sort array to [1,5,6]. Median is 5. Need |5-3|=2 operations to make median 3. All elements satisfy constraints: 1 ≤ 3 and 6 ≥ 3. Total: 2 operations.
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i], k ≤ 109
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code