Minimum operations required to change the array such that | arr [ i ] | Java 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
import java . util . * ; class GFG { static int changeTheArray ( int arr [ ] , int n ) { int minEle = Arrays . stream ( arr ) . min ( ) . getAsInt ( ) ; int maxEle = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; int minOperations = Integer . MAX_VALUE ; 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 ; System . out . println ( changeTheArray ( arr , n ) ) ; } }