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.
Complete the function getMinimumMoves in the editor.
getMinimumMoves has the following parameters:
int price[n]: the prices of itemsint k: the required median
Returns
long integer: the minimum number of moves to make the median of the array exactly k
price = [4, 2, 1, 4, 7] k = 3 return = 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.
1 ≤ n ≤ 10^51 ≤ price[i], k ≤ 10^9- It is guaranteed that
nis odd.
- Maximum Requests in a Time WindowOA · Seen Jul 2026
- Query Type Frequency WindowOA · Seen Jul 2026
- Minimum Number of Non-Empty Disjoint SegmentsOA · Seen Jul 2026
- Spam Text ClassificationOA · Seen Jul 2026
- Parent Process NumberOA · Seen Jun 2026
- Request Retry CountOA · Seen Jun 2026
- Count Ideal NumbersOA · Seen Jun 2026
- Count Descending SubarraysOA · Seen Apr 2026
public long getMinimumMoves(int[] price, int k) {
// write your code here
}