Make the array elements equal by performing given operations minimum number of times | Java Program for the above approach ; 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 ; Driver Code ; Given array ; Size of the array
import java . io . * ; class GFG { static void minOperation ( int a [ ] , int N ) { int totOps = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { totOps += Math . abs ( a [ i ] - a [ i + 1 ] ) ; } int maxOps = Math . max ( Math . abs ( a [ 0 ] - a [ 1 ] ) , Math . abs ( a [ N - 1 ] - a [ N - 2 ] ) ) ; for ( int 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 ] ) ) ; } System . out . println ( totOps - maxOps ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , - 1 , 0 , 1 , 1 } ; int N = arr . length ; minOperation ( arr , N ) ; } }