Minimum operations required to change the array such that | arr [ i ] | Function to return the minimum number of operations required ; Minimum and maximum elements from the array ; To store the minimum number of operations required ; To store the number of operations required to change every element to either ( num - 1 ) , num or ( num + 1 ) ; If current element is not already num ; Add the count of operations required to change arr [ i ] ; Update the minimum operations so far ; Driver code
function changeTheArray ( arr , n ) { let minEle = Math . min ( ... arr ) ; let maxEle = Math . max ( ... arr ) ; let minOperations = Number . MAX_VALUE ; for ( let num = minEle ; num <= maxEle ; num ++ ) { let operations = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( arr [ i ] != num ) { operations += ( Math . abs ( num - arr [ i ] ) - 1 ) ; } } minOperations = Math . min ( minOperations , operations ) ; } return minOperations ; } let arr = [ 10 , 1 , 4 ] ; let n = arr . length ; document . write ( changeTheArray ( arr , n ) ) ;