Make the median of an array equal to a target value using the minimum number of unit increments or decrements.
Problem
You are given an integer array and a target value . In one operation, you may increase or decrease any element by 1.
Return the minimum number of operations needed so that the median of the array becomes exactly .
For an array of length , the median is the element at index after the array is sorted in nondecreasing order.
Idea
Only the values around the median matter after sorting. Your goal is to adjust the middle element to and ensure the elements on the left do not exceed it while the elements on the right do not fall below it in a way that would change the median away from .
Input Format
- The first line contains an integer .
- The second line contains integers representing the array.
- The third line contains an integer .
Output Format
Print one integer: the minimum number of operations required.
Constraints
- Elements can be negative or positive integers
- Each operation changes one element by exactly 1
Example 1
Input
n = 3 nums = [2, 5, 6] k = 5
Output
0
Explanation
After sorting, the median is already 5, so no operations are needed.
Example 2
Input
n = 5 nums = [2, 4, 6, 8, 10] k = 5
Output
1
Explanation
After sorting, the median is 6. Decrease it by 1 to make the median equal to 5.
Show 1 more example
Example 3
Input
n = 5 nums = [1, 2, 3, 4, 5] k = 3
Output
0
Explanation
The sorted median is already 3.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.