Minimum operations required to change the array such that | arr [ i ] | Python3 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 math NEW_LINE import sys NEW_LINE def changeTheArray ( arr , n ) : NEW_LINE INDENT minEle = min ( arr ) NEW_LINE maxEle = max ( arr ) NEW_LINE minOperations = sys . maxsize NEW_LINE for num in range ( minEle , maxEle + 1 ) : NEW_LINE INDENT operations = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] != num : NEW_LINE INDENT operations += ( abs ( num - arr [ i ] ) - 1 ) NEW_LINE DEDENT DEDENT minOperations = min ( minOperations , operations ) NEW_LINE DEDENT return minOperations NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 1 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( changeTheArray ( arr , n ) ) NEW_LINE DEDENT