Minimize moves to make Array elements equal by incrementing and decrementing pairs - GeeksforGeeks

05 Aug, 2021
Given an array arr[] of size N, the task is to print the minimum number of moves needed to make all array elements equal by selecting any two distinct indices and then increment the element at the first selected index and decrement the element at the other selected index by 1 in each move. If it is impossible to make all the array elements equal then print “-1“.
Examples: 
Input: arr[] = {5, 4, 1, 10}Output: 5Explanation: One of the possible way to perform operation is:Operation 1: Select the indices 1 and 3 and then increment arr[1] by 1 and decrement arr[3] by 1. Thereafter, the array modifies to {5, 5, 1, 9}.Operation 2: Select the indices 2 and 3 and then increment arr[2] by 1 and decrement arr[3] by 1. Thereafter, the array modifies to {5, 5, 2, 8}.Operation 3: Select the indices 2 and 3 and then increment arr[2] by 1 and decrement arr[3] by 1. Thereafter, the array modifies to {5, 5, 3, 7}.Operation 4: Select the indices 2 and 3 and then increment arr[2] by 1 and decrement arr[3] by 1. Thereafter, the array modifies to {5, 5, 4, 6}.Operation 5: Select the indices 2 and 3 and then increment arr[2] by 1 and decrement arr[3] by 1. Thereafter, the array modifies to {5, 5, 5, 5}.Therefore, the total number of move needed is 5. Also, it is the minimum possible moves needed.
Input: arr[] = {1, 4}Output: -1
Approach: The given problem can be solved based on the following observations: 
It can be observed that in one move the sum of the array remains the same therefore, if the sum of the array is not divisible N then it is impossible to make all the array elements equal.
Otherwise, each array element will be equal to the sum of the array divided by N.
Therefore, the idea is to use the two pointer technique to find the minimum count of moves needed to make all the array elements equal to the sum/N.
Follow the steps below to solve the problem:
Initialize a variable, say ans as 0, to store the count of the moves needed.
Find the sum of the array and store it in a variable say sum.
Now if the sum is not divisible by N then print “-1“. Otherwise, update the sum as sum =sum/N.
Sort the array in ascending order.
Initialize variables, say i as 0 and j as N – 1 to iterate over the array.
Iterate until i is less than j and perform the following steps:If increasing arr[i] to sum is less than decreasing arr[j] to sum then add sum –  arr[i] to the ans, and then update arr[i], and arr[j] and then increment i by 1.Otherwise, add arr[j] – sum to the ans, and update arr[i] and arr[j] and then decrement j by 1.
If increasing arr[i] to sum is less than decreasing arr[j] to sum then add sum –  arr[i] to the ans, and then update arr[i], and arr[j] and then increment i by 1.
Otherwise, add arr[j] – sum to the ans, and update arr[i] and arr[j] and then decrement j by 1.
Finally, after completing the above steps, print the value of stored in ans.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program for the above approach#include <algorithm>#include <iostream>using namespace std; // Function to find the minimum// operations to make the array// elements equalint find(int arr[], int N){  // Stores the sum of the  // array  int Sum = 0;  for (int i = 0; i < N; i++) {    Sum += arr[i];  }  if (Sum % N) {    return -1;  }   // update sum  Sum /= N;   // sort array  sort(arr, arr + N);   // Store the minimum  // needed moves  int ans = 0;  int i = 0, j = N - 1;   // Iterate until i  // is less than j  while (i < j) {    if (Sum - arr[i] < arr[j] - Sum) {       // Increment ans by      // Sum-arr[i]      ans += (Sum - arr[i]);       // update      arr[i] += (Sum - arr[i]);      arr[j] -= (Sum - arr[i]);       // Increment i by 1      i++;    }    else {       // Increment ans by      //arr[j]-Sum      ans += (arr[j] - Sum);       // Update      arr[i] += (arr[j] - Sum);      arr[j] -= (arr[j] - Sum);       // Decrement j by 1      j--;    }  }   // Return the value in ans  return ans;} // Driver codeint main(){   // Given input  int arr[] = { 5, 4, 1, 10 };  int N = sizeof(arr) / sizeof(int);   // Function call  cout << find(arr, N);  return 0;} // This code is contributed by Parth Manchanda
import java.util.Arrays; // Java Program for the above approach class GFG {     // Function to find the minimum    // operations to make the array    // elements equal    public static int find(int arr[], int N)    {               // Stores the sum of the        // array        int Sum = 0;        for (int i = 0; i < N; i++) {            Sum += arr[i];        }        if (Sum % N > 0) {            return -1;        }         // update sum        Sum /= N;         // sort array        Arrays.sort(arr);         // Store the minimum        // needed moves        int ans = 0;        int i = 0, j = N - 1;         // Iterate until i        // is less than j        while (i < j) {            if (Sum - arr[i] < arr[j] - Sum) {                 // Increment ans by                // Sum-arr[i]                ans += (Sum - arr[i]);                 // update                arr[i] += (Sum - arr[i]);                arr[j] -= (Sum - arr[i]);                 // Increment i by 1                i++;            } else {                 // Increment ans by                // arr[j]-Sum                ans += (arr[j] - Sum);                 // Update                arr[i] += (arr[j] - Sum);                arr[j] -= (arr[j] - Sum);                 // Decrement j by 1                j--;            }        }         // Return the value in ans        return ans;    }     // Driver code    public static void main(String args[]) {         // Given input        int arr[] = { 5, 4, 1, 10 };        int N = arr.length;         // Function call        System.out.println(find(arr, N));     }} // This code is contributed by gfgking
# Python program for the above approach # Function to find the minimum# operations to make the array# elements equaldef find(arr, N):     # Stores the sum of the    # array    Sum = sum(arr)     # If sum is not divisible    # by N    if Sum % N:        return -1    else:        # Update sum        Sum //= N         # Sort the array        arr.sort()         # Store the minimum        # needed moves        ans = 0         i = 0        j = N-1         # Iterate until i        # is less than j        while i < j:             # If the Sum-arr[i]            # is less than the            # arr[j]-sum            if Sum-arr[i] < arr[j]-Sum:                 # Increment ans by                # Sum-arr[i]                ans += Sum-arr[i]                 # Update                arr[i] += Sum-arr[i]                arr[j] -= Sum-arr[i]                 # Increment i by 1                i += 1                             # Otherwise,            else:                 # Increment ans by                # arr[j]-Sum                ans += arr[j]-Sum                 # Update                arr[i] += arr[j]-Sum                arr[j] -= arr[j]-Sum                 # Decrement j by 1                j -= 1         # Return the value in ans        return ans # Driver Codeif __name__ == '__main__':         # Given Input    arr = [5, 4, 1, 10]    N = len(arr)         # Function Call    print(find(arr, N))
// C# program for the above approachusing System; class GFG{     // Function to find the minimum// operations to make the array// elements equalpublic static int find(int[] arr, int N){         // Stores the sum of the    // array    int Sum = 0;    int i = 0;         for(i = 0; i < N; i++)    {        Sum += arr[i];    }    if (Sum % N > 0)    {        return -1;    }     // update sum    Sum /= N;     // sort array    Array.Sort(arr);     // Store the minimum    // needed moves    int ans = 0;    i = 0;    int j = N - 1;     // Iterate until i    // is less than j    while (i < j)    {        if (Sum - arr[i] < arr[j] - Sum)        {                         // Increment ans by            // Sum-arr[i]            ans += (Sum - arr[i]);             // update            arr[i] += (Sum - arr[i]);            arr[j] -= (Sum - arr[i]);             // Increment i by 1            i++;        }        else        {                         // Increment ans by            // arr[j]-Sum            ans += (arr[j] - Sum);             // Update            arr[i] += (arr[j] - Sum);            arr[j] -= (arr[j] - Sum);             // Decrement j by 1            j--;        }    }     // Return the value in ans    return ans;} // Driver codestatic public void Main(){         // Given input    int[] arr = { 5, 4, 1, 10 };    int N = arr.Length;     // Function call    Console.WriteLine(find(arr, N));}} // This code is contributed by target_2
<script>         // JavaScript Program for the above approach          // Function to find the minimum        // operations to make the array        // elements equal        function find(arr, N) {             // Stores the sum of the            // array            let Sum = 0;             for (i = 0; i < arr.length; i++) {                Sum = Sum + arr[i];            }             // If sum is not divisible            // by N            if (Sum % N)                return -1;            else {                 // Update sum                Sum = Math.floor(Sum / N);                 // Sort the array                arr.sort(function (a, b) { return a - b });                 // Store the minimum                // needed moves                ans = 0                 i = 0                j = N - 1                 // Iterate until i                // is less than j                while (i < j) {                     // If the Sum-arr[i]                    // is less than the                    // arr[j]-sum                    if (Sum - arr[i] < arr[j] - Sum) {                         // Increment ans by                        // Sum-arr[i]                        ans += Sum - arr[i]                         // Update                        arr[i] += Sum - arr[i]                        arr[j] -= Sum - arr[i]                         // Increment i by 1                        i += 1                    }                    // Otherwise,                    else {                         // Increment ans by                        // arr[j]-Sum                        ans += arr[j] - Sum                         // Update                        arr[i] += arr[j] - Sum                        arr[j] -= arr[j] - Sum                         // Decrement j by 1                        j -= 1                    }                 }            }            // Return the value in ans            return ans;         }         // Driver Code          // Given Input        let arr = [5, 4, 1, 10];        let N = arr.length;         // Function Call        document.write(find(arr, N));      // This code is contributed by Potta Lokesh     </script>
5
Time Complexity: O(N*log(N))Auxiliary Space: O(1)
lokeshpotta20
parthmanchanda81
gfgking
target_2
surinderdawra388
Arrays
Greedy
Sorting
Arrays
Greedy
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Reversal algorithm for array rotation
Window Sliding Technique
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Huffman Coding | Greedy Algo-3
Write a program to print all permutations of a given string