![]() |
VOOZH | about |
Given an array arr[] of positive integers and a value k, you can perform at most k operations. In each operation, you may increment any one element of the array by 1. Find the maximum median that can be achieved after performing at most k such operations.
Note: If the array has even length, the median is calculated as (arr[n/2] + arr[n/2 - 1]) / 2 after sorting the array.
Example:
Input: arr[] = [1, 3, 4, 5], k = 3
Output: 5
Explanation: We can add +2 to the second element and +1 to the third element to get the array [1, 5, 5, 5]. After sorting, the array remains [1, 5, 5, 5]. Since the length is even, the median is (5 + 5) / 2 = 5.Input: arr[] = [1, 3, 6, 4, 2], k = 10
Output: 7
Explanation: After applying operations optimally, we can transform the array to [1, 3, 7, 7, 7] (one possible way). Sorted array becomes [1, 3, 7, 7, 7]. Since the length is odd, the median is the middle element 7.
Table of Content
The idea is to try every possible median value from the current median up to currentMedian + k, and check if we can make the median at least that value using β€ k operations.
5
The idea is to maximize the median by optimally using the given k increments. We sort the array so that increasing elements in the right half raises the median.
We apply binary search on the answer, i.e., on possible median values from current median to median + k. For each candidate median, we check if it can be achieved within k by incrementing the required elements.
Why the Feasibility Function is Monotonic:
If it's possible to achieve a median value x using β€ k operations, then it's also possible to achieve any median β€ x, because it would require equal or fewer increments.
Conversely, if it's not possible to achieve x, then any median > x will require more increments, so it will also be infeasible.
This increasing/infeasible pattern makes the function monotonic, which is a key condition for applying binary search on the answer.
Step-by-Step Implementation:
5
Time Complexity: O(n Γ log k), binary search runs in log k steps over the possible median values. Each step calls isPossible, which checks up to n elements to validate the current median.
Auxiliary Space: O(1), only a constant amount of extra space is used for variables. All operations are done in-place without additional data structures.