555. Minimum Operations to Make Median of Array Equal to Target

HardBinary SearchSortingGreedy

Given an array and a target, in one operation you may increase or decrease any element by 1. Return the minimum number of operations to make the median of the array equal to the target. The median is the middle element after sorting; for an even length, it is the element at index n/2 (the upper-middle). Input: '[nums], target'.

Input: '[nums], target'.

Output: Integer — the minimum operations.

Examples

Example 1
Input: [2,5,6,8,5], 4
Output: 2
Explanation: Lower the median element to 4.
Example 2
Input: [2,5,6,8,5], 7
Output: 3
Explanation: Raise elements to push the median to 7.
Example 3
Input: [6], 3
Output: 3
Explanation: Single element to target.

Constraints

Asked by

AmazonGoogleMicrosoftMetaAdobe
Solve this problem in the editor →