Skip to main content
Back to problems
#3107
Medium Algorithms

Minimum operations to make median of array equal to k

Array Greedy Sorting
47.7% acceptance
Feb 23, 2026
165
186
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.

Solution

Rust
Time O(n log n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_operations_to_make_median_k(nums: Vec<i32>, k: i32) -> i64 {
    let mut sorted = nums.clone();
    sorted.sort_unstable();
    let n = sorted.len();
    let median_idx = n / 2;
    let mut ops: i64 = 0;

    // Elements in the lower half (index < median_idx) that are > k must be reduced
    for i in 0..median_idx {
      if sorted[i] > k {
        ops += (sorted[i] - k) as i64;
      }
    }

    // The median element itself
    ops += (sorted[median_idx] - k).abs() as i64;

    // Elements in the upper half (index > median_idx) that are < k must be raised
    for i in (median_idx + 1)..n {
      if sorted[i] < k {
        ops += (k - sorted[i]) as i64;
      }
    }

    ops
  }
}