FastPrepFastPrep
Problem Brief

Get Minimum Moves

OA
See IBM online assessment and hiring insights

A shopkeeper sells n items where the price of the jth item is price[j]. To maintain balance, the shopkeeper wishes to adjust the price of items such that the median of prices is exactly k. In one move, the shopkeeper can increase or decrease the price of any item by 1, and the shopkeeper can perform this move any number of times.

Find the minimum number of moves in which the median of prices becomes exactly k.

Note: The index of the median of an array of m sorted elements, where m is odd, is (m+1)/2. For example, [2, 5, 4, 1, 1, 1, 6] sorted is [1, 1, 1, 2, 4, 5, 6]. Its length is 7 so the median is at index (7 + 1)/2 = 4 using 1-based indexing. The median is 2.

Function Description

Complete the function getMinimumMoves in the editor.

getMinimumMoves has the following parameters:

  1. int price[n]: the prices of items
  2. int k: the required median

Returns

long integer: the minimum number of moves to make the median of the array exactly k

1Example 1

Input
price = [4, 2, 1, 4, 7], k = 3
Output
1
Explanation

Decrease price[0] by 1, the resulting array is [3, 2, 1, 4, 7]; on sorting, this becomes [1, 2, 3, 4, 7] whose median equals k = 3. Thus, in one move, the median becomes 3 and the answer is 1.

Constraints

Limits and guarantees your solution can rely on.

  • 1 ≤ n ≤ 10^5
  • 1 ≤ price[i], k ≤ 10^9
  • It is guaranteed that n is odd.
public long getMinimumMoves(int[] price, int k) {
    // write your code here
}
Input

price

[4, 2, 1, 4, 7]

k

3

Output

1

Sign in to submit your solution.