Open In App

Minimizing operations for equalizing Array elements

Last Updated : 04 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array A[] of length N (N>=2) along with an integer X. You are allowed to select two elements A[i] and A[j], such that the absolute difference between their indices is X. Formally, abs (i – j) = X and then decrement one element and increment the other, the task is to output the minimum number of operations required to make all elements of A[] equal. If not possible to make them equal, then output -1.

Note: For decrementing an element must be greater than or equal to 1.

Examples:

Input: N = 5, D = 2, A[] = {2, 8, 10, 4, 6}
Output: 6
Explanation:
1st Operation: Choose A[3] and A[1], because abs(3-1) = 2, then decrement A[3] and increment A[1]. After that A[] = {3, 8, 9, 4, 6}.
2nd Operation: Choose A[3] and A[1] again then decrement A[3] and increment A[1]. After that A[] = {4, 8, 8, 4, 6}.
3rd Operation: Choose A[3] and A[1], decrement A[3] and increment A[1]. After that A[] = {5, 8, 7, 4, 6}.
4th Operation: Choose A[3] and A[1], decrement A[3] and increment A[1]. After that A[] = {6, 8, 6, 4, 6}.
5th Operation: Choose A[2] and A[4] as abs(2-4) = 2, decrement A[2] and increment A[4]. After that A[] = {6, 7, 6, 5, 6}.
6th Operation: Choose A[2] and A[4] again, decrement A[2] and increment A[4]. After that A[] = {6, 6, 6, 6, 6}.
Now it can be verified that all the elements are equal. 6 are the minimum operations required to do so.

Input: N = 6, D = 1, A[] = {3, 4, 5, 1, 4, 5}
Output: -1
Explanation: It can be verified that all elements can’t made equal by using the given operation.

Approach: To solve the problem follow the below idea:

  • Calculate the sum of elements present in A[]. If the sum is not divisible by N, print -1 and because it’s impossible to make all elements equal in this case.
  • If the sum is divisible by N, Then calculate the average value of the elements.
  • Then number of moves required to make all elements equal can be determined by iterating over the array in steps of X and adjusting the elements to the average value. The runningSum variable keeps track of the difference between the sum of the adjusted elements and the desired total sum (which is avg * number of elements).
  • If at the end of the adjustment process runningSum is not zero, it means it’s impossible to make all elements equal, so it sets requied moves to -1.
  • Finally, it prints the number of moves.

Steps were taken to solve the problem:

  • Create a variable let say sum to store the sum of all elements.
  • Calculate sum using iterating over A[].
  • If (sum % N != 0), then output -1.
  • Create a variable let say avg to store the average of all elements an initialize it with (sum/N).
  • Create a variable let say moves to store the minimum operations required.
  • Run a loop for i = 0 to i < X and i++, follow below mentioned steps under the scope of loop:
    • Create a variable let say runningSum and initialize it equal to 0.
    • Run a loop for j = i to j < N and j+=X, follow below mentioned steps under the scope of loop:
      • runningSum += A[j];
      • runningSum -= avg;
      • moves += Math.abs(runningSum)
    • if (runningSum != 0), then set moves = -1 and break
  • Output the value of moves.

Code to implement the approach:

C++




// C++ Implementation
#include <iostream>
#include <vector>
using namespace std;
 
// Function to calculate the minimum operations required
void min_operations(int N, int X, vector<int>& A) {
    // Variable for storing sum of A[]
    long long sum = 0;
 
    // Loop for calculating sum
    for (int i = 0; i < N; i++) {
        sum += A[i];
    }
 
    // Checking for the validity, We can make
    // All elements equal or not
    if (sum % N != 0) {
        cout << "-1" << endl;
        return;
    }
 
    // Average of A[]
    long long avg = sum / N;
 
    // Variable to store min_operations
    long long moves = 0;
 
    // Apply logic described in Concept
    // of approach section
    for (int i = 0; i < X; i++) {
        long long runningSum = 0;
        for (int j = i; j < N; j += X) {
            runningSum += A[j];
            runningSum -= avg;
            moves += abs(runningSum);
        }
        if (runningSum != 0) {
            moves = -1;
            break;
        }
    }
 
    // Printing the minimum moves required
    cout << moves << endl;
}
 
// Driver code
int main() {
    // Inputs
    int N = 5;
    int X = 2;
    vector<int> A = {2, 8, 10, 4, 6};
 
    // Function call
    min_operations(N, X, A);
 
    return 0;
}
 
// This code is contributed by Sakshi


Java




// Java code to implement the approach
 
import java.io.*;
import java.util.*;
 
// Driver Class
class Main {
    // Driver Function
    public static void main(String[] args)
        throws IOException
    {
        // Inputs
        int N = 5;
        int X = 2;
        int[] A = { 2, 8, 10, 4, 6 };
 
        // Function call
        min_operations(N, X, A);
    }
 
    // Method to print the minmimum
    // operations required
    public static void min_operations(int N, int X, int[] A)
    {
        // Variable for storing sum of A[]
        long sum = 0;
 
        // Loop for calculating su,
        for (int i = 0; i < N; i++) {
            sum += A[i];
        }
 
        // Checking for the validity, We can make
        // All elements equal or not
        if (sum % N != 0) {
            System.out.println("-1");
        }
 
        // Averga of A[]
        long avg = sum / N;
 
        // Variable to store min_operations
        long moves = 0;
 
        // Apply logic described in Concept
        // of approach section
        for (int i = 0; i < X; i++) {
            long runningSum = 0;
            for (int j = i; j < N; j += X) {
                runningSum += A[j];
                runningSum -= avg;
                moves += Math.abs(runningSum);
            }
            if (runningSum != 0) {
                moves = -1;
                break;
            }
        }
 
        // Printing the minimum moves required
        System.out.println(moves);
    }
}


Python3




# Python Code
 
# Function to calculate the minimum operations required
def min_operations(N, X, A):
    # Variable for storing sum of A[]
    total_sum = sum(A)
 
    # Checking for the validity, We can make
    # All elements equal or not
    if total_sum % N != 0:
        print("-1")
        return
 
    # Average of A[]
    avg = total_sum // N
 
    # Variable to store min_operations
    moves = 0
 
    # Apply logic described in Concept
    # of approach section
    for i in range(X):
        running_sum = 0
        for j in range(i, N, X):
            running_sum += A[j]
            running_sum -= avg
            moves += abs(running_sum)
 
        if running_sum != 0:
            moves = -1
            break
 
    # Printing the minimum moves required
    print(moves)
 
# Driver code
if __name__ == "__main__":
    # Inputs
    N = 5
    X = 2
    A = [2, 8, 10, 4, 6]
 
    # Function call
    min_operations(N, X, A)
 
# This code is contributed by guptapratik


C#




using System;
using System.Collections.Generic;
 
class Program
{
    // Function to calculate the minimum operations required
    static void MinOperations(int N, int X, List<int> A)
    {
        // Variable for storing sum of A[]
        long sum = 0;
 
        // Loop for calculating sum
        foreach (int value in A)
        {
            sum += value;
        }
 
        // Checking for the validity, We can make
        // All elements equal or not
        if (sum % N != 0)
        {
            Console.WriteLine("-1");
            return;
        }
 
        // Average of A[]
        long avg = sum / N;
 
        // Variable to store min_operations
        long moves = 0;
 
        // Apply logic described in Concept
        // of approach section
        for (int i = 0; i < X; i++)
        {
            long runningSum = 0;
            for (int j = i; j < N; j += X)
            {
                runningSum += A[j];
                runningSum -= avg;
                moves += Math.Abs(runningSum);
            }
            if (runningSum != 0)
            {
                moves = -1;
                break;
            }
        }
 
        // Printing the minimum moves required
        Console.WriteLine(moves);
    }
 
    // Driver code
    static void Main()
    {
        // Inputs
        int N = 5;
        int X = 2;
        List<int> A = new List<int> { 2, 8, 10, 4, 6 };
 
        // Function call
        MinOperations(N, X, A);
    }
}
 
// This code is contributed by shivamgupta310570


Javascript




// Javascript code to implement the approach
 
// Method to print the minmimum
// operations required
function min_operations(N, X, A) {
    // Variable for storing sum of A[]
    let sum = 0;
 
    // Loop for calculating su,
    for (let i = 0; i < N; i++) {
        sum += A[i];
    }
 
    // Checking for the validity, We can make
    // All elements equal or not
    if (sum % N !== 0) {
        console.log("-1");
    }
 
    // Average of A[]
    let avg = Math.floor(sum / N);
 
    // Variable to store min_operations
    let moves = 0;
 
    // Apply logic described in Concept
    // of approach section
    for (let i = 0; i < X; i++) {
        let runningSum = 0;
        for (let j = i; j < N; j += X) {
            runningSum += A[j];
            runningSum -= avg;
            moves += Math.abs(runningSum);
        }
        if (runningSum !== 0) {
            moves = -1;
            break;
        }
    }
 
    // Printing the minimum moves required
    console.log(moves);
}
 
// Driver code
// Inputs
let N = 5;
let X = 2;
let A = [2, 8, 10, 4, 6];
 
// Function call
min_operations(N, X, A);
 
// This code is contributed by ragul21


Output

6






Time Complexity: O(N)
Auxillary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads