Minimum number of elements to add to make median equals x | Javascript program to find minimum number of elements to add so that its median equals x . ; No . of elements equals to x , that is , e . ; No . of elements greater than x , that is , h . ; No . of elements smaller than x , that is , l . ; Subtract the no . of elements that are equal to x . ; Driver code
function minNumber ( a , n , x ) { let l = 0 , h = 0 , e = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( a [ i ] == x ) e ++ ; else if ( a [ i ] > x ) h ++ ; else if ( a [ i ] < x ) l ++ ; } let ans = 0 ; if ( l > h ) ans = l - h ; else if ( l < h ) ans = h - l - 1 ; return ans + 1 - e ; } let x = 10 ; let a = [ 10 , 20 , 30 ] ; let n = a . length ; document . write ( minNumber ( a , n , x ) ) ;