Skip to main content
Back to problems
Leetcode
Medium
Arrays
Sorting
Greedy
Minimum Operations To Make Median Of Array Equal To K

Make the median of an array equal to a target value using the minimum number of unit increments or decrements.

Acceptance 0%
Problem Statement

Problem

You are given an integer array and a target value kk. 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 kk.

For an array of length nn, the median is the element at index n/2\lfloor n/2 \rfloor 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 kk 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 kk.

Input Format

  • The first line contains an integer nn.
  • The second line contains nn integers representing the array.
  • The third line contains an integer kk.

Output Format

Print one integer: the minimum number of operations required.

Constraints

  • 1n1051 \le n \le 10^5
  • Elements can be negative or positive integers
  • Each operation changes one element by exactly 1
Examples
Sample cases returned by the problem API.

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.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.