A desert customs post inspects a caravan of n carts. Each cart carries a declared cargo weight. Regulations require that, when the weights are sorted from lightest to heaviest, the median declared weight equals an audit target k. The median is the value sitting at the middle position after sorting; when n is even and there are two middle values, the larger of the two counts as the median.
Before the audit begins, an inspector may repeatedly pick any single cart and change its declared weight by exactly 1 unit (either up or down) — each such change is one operation. Determine the minimum number of operations needed so that the median of the (possibly modified) weights equals exactly k.
n.n integers w_1, w_2, ..., w_n — the declared weight of each cart.k — the customs audit target.Print a single integer: the minimum number of weight-adjustment operations required.
Example 1
Input
5 3 7 8 10 15 9
Expected
1
Explanation
Sorting the weights gives [3, 7, 8, 10, 15]; with 5 carts the median is the value at the middle index, 8. Since 8 is less than the target 9, the inspector raises that cart's weight by 1 unit (one operation) to reach 9. No other cart needs adjustment because the next-heavier cart is already above 9. Minimum operations: 1.
Example 2
Input
4 4 12 9 1 6
Expected
3
Explanation
Sorting the weights gives [1, 4, 9, 12]; with 4 carts (an even count) the two middle values are 4 and 9, and by the tie-break rule the median is the larger one, 9. To bring 9 down to the target 6 requires changing that cart's weight by 3 units, one unit per operation, so 3 operations are needed. The cart weighing 4 is already at or below 6 and needs no change. Minimum operations: 3.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →