Minimize moves to make Array elements equal by incrementing and decrementing pairs
Last Updated :
21 Mar, 2023
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: 5
Explanation:
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.
- Finally, after completing the above steps, print the value of stored in ans.
Below is the implementation of the above approach:
C++
// C++ Program for the above approach
#include <algorithm>
#include <iostream>
using namespace std;
// Function to find the minimum
// operations to make the array
// elements equal
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) {
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 code
int 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
Java
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
Python3
# Python program for the above approach
# Function to find the minimum
# operations to make the array
# elements equal
def 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 Code
if __name__ == '__main__':
# Given Input
arr = [5, 4, 1, 10]
N = len(arr)
# Function Call
print(find(arr, N))
C#
// C# program for the above approach
using System;
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;
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 code
static 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
JavaScript
<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>
Time Complexity: O(N*log(N))
Auxiliary Space: O(1)
Another Approach:
- Compute the sum of all elements in the array and divide it by N to find the target value (the value that all elements in the array should be equal to).
- Iterate over the array, and for each element:
- Compute the difference between the current element and the target value.
- If the difference is odd, return -1 (because we can't make all elements equal by incrementing and decrementing in pairs).
- Otherwise, add the absolute value of the difference to a variable count (this represents the number of moves needed to make the current element equal to the target value).
- Return the count.
Below is the implementation of above approach:
C++
#include <algorithm>
#include <iostream>
using namespace std;
int find(int arr[], int N) {
int Sum = 0;
for (int i = 0; i < N; i++) {
Sum += arr[i];
}
if (Sum % N) {
return -1;
}
Sum /= N;
sort(arr, arr + N);
int ans = 0, i = 0;
while (i < N) {
int j = i + 1;
while (j < N && arr[j] <= Sum) {
j++;
}
if (j == N) {
break;
}
ans += j - i;
arr[i] += j - i;
arr[j] -= j - i;
i++;
}
return ans;
}
int main() {
int arr[] = { 5, 4, 1, 10 };
int N = sizeof(arr) / sizeof(int);
cout << find(arr, N); // Output: 5
return 0;
}
Java
// Java implementation of a function to
// find the minimum number of moves required
// to make all elements of an array equal
import java.util.Arrays;
public class Main {
// Function to find the minimum number of moves required
// to make all elements of an array equal
static int find(int arr[], int N) {
// Calculate the sum of all the elements of the array
int Sum = 0;
for (int i = 0; i < N; i++) {
Sum += arr[i];
}
// If the sum is not divisible by N, we cannot make all
// elements equal by adding or subtracting from each other.
// Hence, return -1.
if (Sum % N != 0) {
return -1;
}
// Calculate the target sum by dividing the sum of
// all elements by N.
int targetSum = Sum / N;
// Sort the array in non-decreasing order
Arrays.sort(arr);
int ans = 0, i = 0;
while (i < N) {
// Find the index j of the first element in the array
// that is greater than the target sum.
int j = i + 1;
while (j < N && arr[j] <= targetSum) {
j++;
}
// If j equals N, it means that all the remaining
// elements in the array are less than or equal to
// the target sum, and hence, we cannot make them
// equal to the target sum by adding or subtracting
// from each other. Therefore, break out of the loop.
if (j == N) {
break;
}
// Calculate the number of moves required to make
// elements arr[i] to arr[j-1] equal to the target sum.
ans += j - i;
arr[i] += j - i;
arr[j] -= j - i;
i++;
}
return ans;
}
public static void main(String[] args) {
int arr[] = { 5, 4, 1, 10 };
int N = arr.length;
System.out.println(find(arr, N)); // Output: 5
}
}
Python3
def find(arr, N):
Sum = sum(arr)
if Sum % N:
return -1
Sum //= N
arr.sort()
ans, i = 0, 0
while i < N:
j = i + 1
while j < N and arr[j] <= Sum:
j += 1
if j == N:
break
ans += j - i
arr[i:i+j-i] = [arr[i] + j - i] * (j - i)
arr[j] -= j - i
i += 1
return ans
arr = [5, 4, 1, 10]
N = len(arr)
print(find(arr, N)) # Output: 5
JavaScript
// Javascript implementation of a function to
// find the minimum number of moves required
// to make all elements of an array equal
// Function to find the minimum number of moves required
// to make all elements of an array equal
function find(arr, N) {
// Calculate the sum of all the elements of the array
let Sum = 0;
for (let i = 0; i < N; i++) {
Sum += arr[i];
}
// If the sum is not divisible by N, we cannot make all
// elements equal by adding or subtracting from each other.
// Hence, return -1.
if (Sum % N) {
return -1;
}
// Calculate the target sum by dividing the sum of
// all elements by N.
Sum /= N;
// Sort the array in non-decreasing order
arr.sort((a, b) => a - b);
let ans = 0, i = 0;
while (i < N) {
// Find the index j of the first element in the array
// that is greater than the target sum.
let j = i + 1;
while (j < N && arr[j] <= Sum) {
j++;
}
// If j equals N, it means that all the remaining
// elements in the array are less than or equal to
// the target sum, and hence, we cannot make them
// equal to the target sum by adding or subtracting
// from each other. Therefore, break out of the loop.
if (j == N) {
break;
}
// Calculate the number of moves required to make
// elements arr[i] to arr[j-1] equal to the target sum.
ans += j - i;
arr[i] += j - i;
arr[j] -= j - i;
i++;
}
return ans;
}
let arr = [5, 4, 1, 10];
let N = arr.length;
console.log(find(arr, N)); // Output: 5
C#
using System;
using System.Collections.Generic;
class Gfg{
static int find(int[] arr, int N) {
int Sum = 0, i=0;
for ( i = 0; i < N; i++) {
Sum += arr[i];
}
if (Sum % N !=0) {
return -1;
}
Sum /= N;
Array.Sort(arr);
int ans = 0;
i = 0;
while (i < N) {
int j = i + 1;
while (j < N && arr[j] <= Sum) {
j++;
}
if (j == N) {
break;
}
ans += j - i;
arr[i] += j - i;
arr[j] -= j - i;
i++;
}
return ans;
}
public static void Main(String[] args)
{
int[] arr = { 5, 4, 1, 10 };
int N = arr.Length;
Console.Write(find(arr, N)); // Output: 5
}
}
Time Complexity: O(N), where N is the size of the input array
Auxiliary Space: O(1)
Similar Reads
Minimize moves required to make array elements equal by incrementing and decrementing pairs | Set 2
Given an array arr[] of size N, the task is to print the minimum number of moves required to make all array elements equal by selecting any pair of distinct indices and then increment the element at the first index and decrement the element at the other index by 1 each time. If it is impossible to m
7 min read
Minimize increment or increment and decrement of Pair to make all Array elements equal
Given an array arr[] of size N, the task is to minimize the number of steps to make all the array elements equal by performing the following operations: Choose an element of the array and increase it by 1.Select two elements simultaneously (arr[i], arr[j]) increase arr[i] by 1 and decrease arr[j] by
8 min read
Minimum cost to make Array equal by increment/decrementing elements
Given an array, arr[], and the cost array cost[], the task is to find the minimum cost to make all the array elements equal by incrementing or decrementing the element at any index by 1. The cost of the increment or decrement operation for the element at index i is the cost[i]. Examples: Input: arr[
8 min read
Minimum Increment / decrement to make array elements equal
Given an array of integers where 1 \leq A[i] \leq 10^{18} . In one operation you can either Increment/Decrement any element by 1. The task is to find the minimum operations needed to be performed on the array elements to make all array elements equal. Examples: Input : A[] = { 1, 5, 7, 10 } Output :
7 min read
Minimize steps to make Array elements equal by deleting adjacent pair and inserting bitwise OR
Given an array arr[], consisting of N integers, the task is to find the minimum number of moves required to make all numbers in the resulting array equal. In one move, Take two adjacent numbers arr[i] and arr[i+1], and delete them. Insert the bitwise OR of arr[i] and arr[i+1] at the deleted position
6 min read
Minimum increment and decrement by K of each pair elements required to make all array elements equal
Given an array arr[], the task is to check if it is possible to make all array elements equal by repeatedly choosing a triplet (i, j, k), where i and j are different, and subtract k from arr[i] and add k to arr[j]. Examples: Input: arr[] = {1, 5, 6, 4}Output: YesExplanation:Operations performed: Cho
10 min read
Minimize increments required to make count of even and odd array elements equal
Given an array arr[] of size N, the task is to find the minimum increments by 1 required to be performed on the array elements such that the count of even and odd integers in the given array becomes equal. If it is not possible, then print "-1". Examples: Input: arr[] = {1, 3, 4, 9}Output: 1Explanat
6 min read
Minimize cost of insertions and deletions required to make all array elements equal
Given a sorted array arr[] of size N (1 ? N ? 105) and two integers A and B, the task is to calculate the minimum cost required to make all array elements equal by increments or decrements. The cost of each increment and decrement are A and B respectively. Examples: Input: arr[] = { 2, 5, 6, 9, 10,
11 min read
Minimum increments or decrements by 1 required to make all array elements in AP
Given an array arr[] consisting of N integers, the task is to find the minimum number of increment/decrement by 1 required to be performed on array elements to make all the elements of the given array arr[] in AP. If it is not possible to make the array in AP, then print "-1". Examples: Input: arr[]
11 min read
Minimize increment or decrement operations to make given Array elements consecutive
Given an array, arr[] of size N., The task is to perform minimum increment or decrement operations on the elements of the array, to make all the elements consecutive, Output the minimum sum of all the possible changes(addition and subtractions) required to do the same. Examples: Input: N = 5, arr[]
5 min read