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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int changeTheArray ( int arr [ ] , int n ) { int minEle = * ( std :: min_element ( arr , arr + n ) ) ; int maxEle = * ( std :: max_element ( arr , arr + n ) ) ; int minOperations = INT_MAX ; for ( int num = minEle ; num <= maxEle ; num ++ ) { int operations = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] != num ) { operations += ( abs ( num - arr [ i ] ) - 1 ) ; } } minOperations = min ( minOperations , operations ) ; } return minOperations ; } int main ( ) { int arr [ ] = { 10 , 1 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << changeTheArray ( arr , n ) ; return 0 ; }