Make the array elements equal by performing given operations minimum number of times | C # 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
using System ; public 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 ] ) ) ; } Console . WriteLine ( totOps - maxOps ) ; } static public void Main ( ) { int [ ] arr = { 1 , - 1 , 0 , 1 , 1 } ; int N = arr . Length ; minOperation ( arr , N ) ; } }