Find the minimum value of X for an expression | Function to calculate value of X ; Check for both possibilities ; Driver Code
function valueofX ( ar , n ) { let sum = 0 ; for ( let i = 0 ; i < n ; i ++ ) { sum = sum + ar [ i ] ; } if ( sum % n == 0 ) { return Math . floor ( sum / n ) ; } else { let A = Math . floor ( sum / n ) , B = Math . floor ( sum / n + 1 ) ; let ValueA = 0 , ValueB = 0 ; for ( let i = 0 ; i < n ; i ++ ) { ValueA += ( ar [ i ] - A ) * ( ar [ i ] - A ) ; ValueB += ( ar [ i ] - B ) * ( ar [ i ] - B ) ; } if ( ValueA < ValueB ) { return A ; } else { return B ; } } } let n = 7 ; let arr = [ 6 , 9 , 1 , 6 , 1 , 3 , 7 ] ; document . write ( valueofX ( arr , n ) + " " ) ;