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.

Example 1
Inputnums = [2,5,6,8,5], k = 4
Output2
Subtracting one from nums[1] and nums[4] gives [2, 4, 6, 8, 4], whose median is equal to k.
Example 2
Inputnums = [2,5,6,8,5], k = 7
Output3
Adding one to nums[1] twice and one to nums[2] once gives [2, 7, 7, 8, 5], whose median is equal to k.

Constraints

  • 1 <= nums.length <= 2 * 10^5
  • 1 <= nums[i] <= 10^9
  • 1 <= k <= 10^9

Asked at 1 companies

Practice questions like this out loud in a mock coding interview with a live AI interviewer. First one free.

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, what to keep, what's wrong, and the complexity of your solution.

Sign in to evaluate