c++searchmaxbinary-searchmedian

Maximum Median competitive programming question


You are given an array consisting of N integers. Now you can perform one type of operation on it which is to choose any index i and increment ai by 1 i.e. ai=ai+1. With this operation, you want to maximize the median. Also, you can apply this operation at most K times. The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order.

input: 3 2

1 3 5

output: 5

input: 5 5

1 2 1 1 1

output: 3

I am having a hard time understanding the problem, My thoughts are, they have asked for the maximum median and if we just sort and pick the middle element and increase it with k. Then it would be the maximum median. I've seen some solutions on the internet but I couldn't understand them. Can someone help me out with what to do here?


Solution

  • My thoughts are, they have asked for the maximum median and if we just sort and pick the middle element and increase it with k. Then it would be the maximum median.

    Not really, because once it's incremented that element may very well not be the median anymore. Consider the example 1, 2, 1, 1, 1. The median is 1 (sorted: 1, 1, 1, 1, 2) and if you add all of k = 5 to that element, you'll obtain 1, 1, 6, 1, 2 -> 1, 1, 1, 2, 6. The median would still be 1, which is "wrong".

    Try the following algorithm, instead.