Minimum operations required to change the array such that | arr [ i ] | C # implementation of the approach ; 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
using System ; using System . Linq ; class GFG { static int changeTheArray ( int [ ] arr , int n ) { int minEle = arr . Min ( ) ; int maxEle = arr . Max ( ) ; int minOperations = int . MaxValue ; for ( int num = minEle ; num <= maxEle ; num ++ ) { int operations = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] != num ) { operations += ( Math . Abs ( num - arr [ i ] ) - 1 ) ; } } minOperations = Math . Min ( minOperations , operations ) ; } return minOperations ; } public static void Main ( String [ ] args ) { int [ ] arr = { 10 , 1 , 4 } ; int n = arr . Length ; Console . WriteLine ( changeTheArray ( arr , n ) ) ; } }