Make the array elements equal by performing given operations minimum number of times | Function to calculate the minimum operations of given type required to make the array elements equal ; Stores the total count of operations ; Traverse the array ; Update difference between pairs of adjacent elements ; Store the maximum count of operations ; Rest of the elements ; Total Operation - Maximum Operation ; Given array ; Size of the array
function minOperation ( a , N ) { var totOps = 0 ; for ( i = 0 ; i < N - 1 ; i ++ ) { totOps += Math . abs ( a [ i ] - a [ i + 1 ] ) ; } var maxOps = Math . max ( Math . abs ( a [ 0 ] - a [ 1 ] ) , Math . abs ( a [ N - 1 ] - a [ N - 2 ] ) ) ; for ( i = 1 ; i < N - 1 ; i ++ ) { maxOps = Math . max ( maxOps , Math . abs ( a [ i ] - a [ i - 1 ] ) + Math . abs ( a [ i ] - a [ i + 1 ] ) - Math . abs ( a [ i - 1 ] - a [ i + 1 ] ) ) ; } document . write ( totOps - maxOps ) ; } var arr = [ 1 , - 1 , 0 , 1 , 1 ] ; var N = arr . length ; minOperation ( arr , N ) ;