Minimize moves required to make array elements equal by incrementing and decrementing pairs | Set 2 | Function to find the minimum number of increment and decrement of pairs required to make all array elements equal ; Stores the sum of the array ; If sum is not divisible by N ; Update sum ; Store the minimum number of operations ; Iterate while i is less than N ; Add absolute difference of current element with k to ans ; Increase i bye 1 ; Return the value in ans2 ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find ( vector < int > arr , int N ) { int Sum = 0 ; for ( auto i : arr ) Sum += i ; if ( Sum % N ) return -1 ; int k = Sum / N ; int ans = 0 ; int i = 0 ; while ( i < N ) { ans = ans + abs ( k - arr [ i ] ) ; i += 1 ; } return ans / 2 ; } int main ( ) { vector < int > arr = { 5 , 4 , 1 , 10 } ; int N = arr . size ( ) ; cout << ( find ( arr , N ) ) ; }