Minimum number of elements to add to make median equals x | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minNumber ( int a [ ] , int n , int x ) { int l = 0 , h = 0 , e = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == x ) e ++ ; else if ( a [ i ] > x ) h ++ ; else if ( a [ i ] < x ) l ++ ; } int ans = 0 ; if ( l > h ) ans = l - h ; else if ( l < h ) ans = h - l - 1 ; return ans + 1 - e ; } int main ( ) { int x = 10 ; int a [ ] = { 10 , 20 , 30 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << minNumber ( a , n , x ) << endl ; return 0 ; }