FastPrepGet Minimum Moves

Get Minimum Moves

IBM logoIBM● MediumOA
Learn

Problem statement

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

getMinimumMoves(price: int[], k: int) → long

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

Examples

Example 1

price = [4, 2, 1, 4, 7]k = 3return = 1

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

  • 1 ≤ n ≤ 10^5
  • 1 ≤ price[i], k ≤ 10^9
  • It is guaranteed that n is odd.

More IBM problems

See IBM hiring insights
public long getMinimumMoves(int[] price, int k) {
    // write your code here
}
price[4, 2, 1, 4, 7]
k3
expected1
Checking account…