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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minOperation ( int a [ ] , int N ) { int totOps = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { totOps += abs ( a [ i ] - a [ i + 1 ] ) ; } int maxOps = max ( abs ( a [ 0 ] - a [ 1 ] ) , abs ( a [ N - 1 ] - a [ N - 2 ] ) ) ; for ( int i = 1 ; i < N - 1 ; i ++ ) { maxOps = max ( maxOps , abs ( a [ i ] - a [ i - 1 ] ) + abs ( a [ i ] - a [ i + 1 ] ) - abs ( a [ i - 1 ] - a [ i + 1 ] ) ) ; } cout << totOps - maxOps << endl ; } int main ( ) { int arr [ ] = { 1 , -1 , 0 , 1 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minOperation ( arr , N ) ; return 0 ; }