3107. Minimum Operations to Make Median of Array Equal to K Medium
1/**
2 * [3107] Minimum Operations to Make Median of Array Equal to K
3 *
4 * 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.
5 * Return the minimum number of operations needed to make the median of nums equal to k.
6 * 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.
7 *
8 * <strong class="example">Example 1:
9 * <div class="example-block">
10 * Input: <span class="example-io">nums = [2,5,6,8,5], k = 4</span>
11 * Output: <span class="example-io">2</span>
12 * Explanation:
13 * We can subtract one from nums[1] and nums[4] to obtain [2, 4, 6, 8, 4]. The median of the resulting array is equal to k.
14 * </div>
15 * <strong class="example">Example 2:
16 * <div class="example-block">
17 * Input: <span class="example-io">nums = [2,5,6,8,5], k = 7</span>
18 * Output: <span class="example-io">3</span>
19 * Explanation:
20 * We can add one to nums[1] twice and add one to nums[2] once to obtain [2, 7, 7, 8, 5].
21 * </div>
22 * <strong class="example">Example 3:
23 * <div class="example-block">
24 * Input: <span class="example-io">nums = [1,2,3,4,5,6], k = 4</span>
25 * Output: <span class="example-io">0</span>
26 * Explanation:
27 * The median of the array is already equal to k.
28 * </div>
29 *
30 * Constraints:
31 *
32 * 1 <= nums.length <= 2 * 10^5
33 * 1 <= nums[i] <= 10^9
34 * 1 <= k <= 10^9
35 *
36 */
37pub struct Solution {}
38
39// problem: https://leetcode.com/problems/minimum-operations-to-make-median-of-array-equal-to-k/
40// discuss: https://leetcode.com/problems/minimum-operations-to-make-median-of-array-equal-to-k/discuss/?currentPage=1&orderBy=most_votes&query=
41
42// submission codes start here
43
44impl Solution {
45 pub fn min_operations_to_make_median_k(nums: Vec<i32>, k: i32) -> i64 {
46
47 }
48}
49
50// submission codes end
51
52#[cfg(test)]
53mod tests {
54 use super::*;
55
56 #[test]
57 fn test_3107() {
58 }
59}
60
Back
© 2025 bowen.ge All Rights Reserved.