Get Minimum Moves
Updated
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:
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
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^51 ≤ price[i], k ≤ 10^9- It is guaranteed that
nis odd.
More IBM interview questions
- Missing IntervalsOA · Seen Nov 2026
- Last Object Exit TimeOA · Seen Nov 2026
- Count Peaks and ValleysOA · Seen Nov 2026
- Count Strictly Increasing Contiguous WindowsOA · Seen Nov 2026
- Total Each Letter's Count in an Encoded StringOA · Seen Nov 2026
- Count Servers With No Requests in a Time WindowOA · Seen Nov 2026
- Alternate Odd and Even Numbers with Two GoroutinesPHONE SCREEN · Seen Nov 2026
- Longest Substring Without Repeating CharactersPHONE SCREEN · Seen Nov 2026
- Maximum Easy Tasks After RearrangingOA · Seen Nov 2026
- Longest Palindromic SubstringPHONE SCREEN · Seen Oct 2026
Similar questions at other companies
- Hiking Club Fastest PaceInfosys · OAInfosys interview questions
- Find Minimum TimeAlphaSense · OA
- Find Minimum TimeBlackRock · OABlackRock interview questions
- Minimum Cost K-Capable ModelsMicrosoft · OAMicrosoft interview questions
- Minimum Cost of Every K-Capable Model SetTikTok · OATikTok interview questions
- Maximum Distinct Values After Unit AdjustmentsBirla Pivot · OA
- Maximize Revenue from Decreasing InventoryChubb · OAChubb interview questions
- Minimum Distinct Prefix CostGoldman Sachs · OAGoldman Sachs interview questions
- Maximize Minimum Deployment DifficultyJP Morgan Chase · OAJP Morgan Chase interview questions
- Latest Arrival to Catch a BusAutodesk · OAAutodesk interview questions