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 ; Given array ; Given number of operation ; Size of array ; Sort the array ; Function call
function possible ( arr , N , mid , K ) { let add = 0 ; for ( let i = parseInt ( N / 2 , 10 ) - ( N + 1 ) % 2 ; i < N ; ++ i ) { if ( mid - arr [ i ] > 0 ) { add += ( mid - arr [ i ] ) ; if ( add > K ) return false ; } } if ( add <= K ) return true ; else return false ; } function findMaxMedian ( arr , N , K ) { let low = 1 ; let mx = 0 ; for ( let i = 0 ; i < N ; ++ i ) { mx = Math . max ( mx , arr [ i ] ) ; } let high = K + mx ; while ( low <= high ) { let mid = parseInt ( ( high + low ) / 2 , 10 ) ; if ( possible ( arr , N , mid , K ) ) { low = mid + 1 ; } else { high = mid - 1 ; } } if ( N % 2 == 0 ) { if ( low - 1 < arr [ parseInt ( N / 2 ) ] ) { return parseInt ( ( arr [ parseInt ( N / 2 ) ] + low - 1 ) / 2 , 10 ) ; } } return low - 1 ; } let arr = [ 1 , 3 , 6 ] ; let K = 10 ; let N = arr . length ; arr . sort ( ) ; document . write ( findMaxMedian ( arr , N , K ) ) ;