Maximize median after doing K addition operation on the Array | Function to check operation can be perform or not ; Number of operation to perform s . t . mid is median ; If mid is median of the array ; Function to find max median of the array ; Lowest possible median ; Highest possible median ; Checking for mid is possible for the median of array after doing at most k operation ; Return the max possible ans ; Driver Code ; Given array ; Given number of operation ; Size of array ; Sort the array ; Function call
def possible ( arr , N , mid , K ) : NEW_LINE INDENT add = 0 NEW_LINE for i in range ( N // 2 - ( N + 1 ) % 2 , N ) : NEW_LINE INDENT if ( mid - arr [ i ] > 0 ) : NEW_LINE INDENT add += ( mid - arr [ i ] ) NEW_LINE if ( add > K ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT if ( add <= K ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def findMaxMedian ( arr , N , K ) : NEW_LINE INDENT low = 1 NEW_LINE mx = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT mx = max ( mx , arr [ i ] ) NEW_LINE DEDENT high = K + mx NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( high + low ) // 2 NEW_LINE if ( possible ( arr , N , mid , K ) ) : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT if ( N % 2 == 0 ) : NEW_LINE INDENT if ( low - 1 < arr [ N // 2 ] ) : NEW_LINE INDENT return ( arr [ N // 2 ] + low - 1 ) // 2 NEW_LINE DEDENT DEDENT return low - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 6 ] NEW_LINE K = 10 NEW_LINE N = len ( arr ) NEW_LINE arr = sorted ( arr ) NEW_LINE print ( findMaxMedian ( arr , N , K ) ) NEW_LINE DEDENT