Open In App

Minimum operations for balancing Array difference

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

Given an integer array A[] consisting of N integers, find the minimum number of operations needed to reduce the difference between the smallest and largest elements in the array to at most 1. In each operation, you can choose two elements and increment one while decrementing the other.

Examples:

Input: N = 6, A = {5, 8, 4, 55, 35, 74}
Output: 73

Input: N = 4, A = {2, 2, 2, 7}
Output: 3
Explanation: In 1st operation, we can increment index 0 and decrease index 3, so A = {3, 2, 2, 6}
In 2nd operation, we can increment index 1 and decrease index 3, so A = {3, 3, 2, 5}
In 3rd operation, we can increment index 2 and decrease index 3, so A = {3, 3, 3, 4}
Now, we can see that the difference between the smallest and largest elements in array A is (4-3) = 1.

Approach: To solve the problem follow the below idea:

The main idea is to calculate the average of the array, sort it in ascending order, and then distribute the excess sum (if any) among the smallest elements from the largest ones to minimize the difference between the minimum and maximum values. Finally, it outputs half of the total operations needed since each operation involves increasing one element and decreasing another.

Steps to implement the above approach:

  • First, we take the input integer N, representing the size of the array, followed by N integers representing the elements of the array A.
  • Calculate the average: The code calculates the sum of all elements in the array A using accumulate, and then divides the sum by N to get the average AVG.
  • Handle edge case: If the array size is 1, which means there is only one element in the array. In this case, the difference between the minimum and maximum values of the array is already 0, so the code prints 0 and returns.
  • Find the remainder: The code calculates the remainder REMAINDER by dividing the sum of the elements by N.
  • Sort the array: The code sorts the array A in ascending order.
  • Traverse the array and calculate the minimum number of operations: The code uses two loops to traverse the sorted array A. The first loop iterates from the largest element in the array, and the second loop iterates from the smallest element. The idea is to distribute the excess sum (if any) to the smallest elements from the largest ones to minimize the difference.
  • Increment and decrement operations: For the elements with indices from N-1 to N-1-REMAINDER, the code performs increment operations to move them closer to AVG+1. For the elements with indices from 0 to N-1-REMAINDER, the code performs decrement operations to move them closer to AVG.
  • Calculate the total number of operations: The code keeps track of the total number of operations required in the variable ANS.
  • Finally, the code prints the minimum number of operations needed to make the difference between the smallest and largest elements in the array at most one. The result is half of the total operations (ANS/2) since each operation involves increasing one element and decreasing another.

Below is the implementation of the above algorithm:

C++




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
void MinOperations(vector<int>& A, int N)
{
    if (N == 1) {
        cout << 0 << endl;
        return;
    }
 
    // Calculate the sum of all
    // elements in the array
    int SUM = accumulate(A.begin(), A.end(), 0ll);
 
    // Calculate the average of the array
    int AVG = SUM / N;
 
    // Calculate the remainder when sum
    // is divided by N
    int REMAINDER = SUM % N;
 
    // Initialize a variable to store the total
    // number of operations
    int ANS = 0;
 
    // Sort the array in ascending order
    sort(A.begin(), A.end());
 
    // Traverse the largest elements and perform
    // increment operations to minimize the difference
    for (int i = N - 1; i > N - 1 - REMAINDER; i--) {
 
        // Increase the current
        // element to (AVG + 1)
        ANS += abs(A[i] - (AVG + 1));
    }
 
    // Traverse the remaining elements and perform
    // decrement operations to minimize the difference
    for (int i = 0; i <= N - 1 - REMAINDER; i++) {
 
        // Decrease the current element to AVG
        ANS += abs(A[i] - AVG);
    }
 
    // Output half of the total operations
    // since each operation involves increasing
    // one element and decreasing another
    cout << ANS / 2 << endl;
}
 
// Drivers code
int main()
{
    vector<int> arr = { 2, 2, 2, 7 };
    int N = 4;
 
    // Function Call
    MinOperations(arr, N);
    return 0;
}


Java




// Java code for the above approach:
 
import java.util.Arrays;
 
public class Main {
    public static void minOperations(int[] A, int N) {
        if (N == 1) {
            System.out.println(0);
            return;
        }
 
        // Calculate the sum of all elements in the array
        long sum = Arrays.stream(A).asLongStream().sum();
 
        // Calculate the average of the array
        int avg = (int) (sum / N);
 
        // Calculate the remainder when sum is divided by N
        int remainder = (int) (sum % N);
 
        // Initialize a variable to store the total number of operations
        int ans = 0;
 
        // Sort the array in ascending order
        Arrays.sort(A);
 
        // Traverse the largest elements and perform increment operations to minimize the difference
        for (int i = N - 1; i > N - 1 - remainder; i--) {
            // Increase the current element to (avg + 1)
            ans += Math.abs(A[i] - (avg + 1));
        }
 
        // Traverse the remaining elements and perform decrement operations to minimize the difference
        for (int i = 0; i <= N - 1 - remainder; i++) {
            // Decrease the current element to avg
            ans += Math.abs(A[i] - avg);
        }
 
        // Output half of the total operations since each operation involves increasing
        // one element and decreasing another
        System.out.println(ans / 2);
    }
 
    public static void main(String[] args) {
        int[] arr = { 2, 2, 2, 7 };
        int N = 4;
 
        // Function Call
        minOperations(arr, N);
    }
}
 
//this code is contributed by uttamdp_10


Python




if __name__ == "__main__":
    N = 4
    A = [2, 2, 2, 7]
 
    if N == 1:
        print(0)
# Calculate the sum of all elements in the array
    SUM = sum(A)
 
  # Calculate the average of the array
    AVG = SUM // N
 
    # Calculate the remainder when sum is divided by N
    REMAINDER = SUM % N
 
    # Initialize a variable to store the total number of operations
    ANS = 0
 
# Sort the array in ascending order
    A.sort()
 
    # Traverse the largest elements and perform increment operations to minimize the difference
    for i in range(N - 1, N - 1 - REMAINDER, -1):
      # Increase the current element to (AVG + 1)
        ANS += abs(A[i] - (AVG + 1))
 
    # Traverse the remaining elements and perform decrement operations to minimize the difference
    for i in range(N - 1 - REMAINDER + 1):
      # Decrease the current element to AVG
        ANS += abs(A[i] - AVG)
 # Output half of the total operations since each operation involves increasing one element and decreasing another
    print(ANS // 2)


C#




// C# code for the above approach:
 
using System;
using System.Linq;
 
public class MainClass
{
    public static void MinOperations(int[] A, int N)
    {
        if (N == 1)
        {
            Console.WriteLine(0);
            return;
        }
 
        // Calculate the sum of all elements in the array
        long sum = A.Sum();
 
        // Calculate the average of the array
        int avg = (int)(sum / N);
 
        // Calculate the remainder when sum is divided by N
        int remainder = (int)(sum % N);
 
        // Initialize a variable to store the total number of operations
        int ans = 0;
 
        // Sort the array in ascending order
        Array.Sort(A);
 
        // Traverse the largest elements and perform increment operations to minimize the difference
        for (int i = N - 1; i > N - 1 - remainder; i--)
        {
            // Increase the current element to (avg + 1)
            ans += Math.Abs(A[i] - (avg + 1));
        }
 
        // Traverse the remaining elements and perform decrement operations to minimize the difference
        for (int i = 0; i <= N - 1 - remainder; i++)
        {
            // Decrease the current element to avg
            ans += Math.Abs(A[i] - avg);
        }
 
        // Output half of the total operations since each operation involves increasing
        // one element and decreasing another
        Console.WriteLine(ans / 2);
    }
 
    public static void Main(string[] args)
    {
        int[] arr = { 2, 2, 2, 7 };
        int N = 4;
 
        // Function Call
        MinOperations(arr, N);
    }
}
 
// This code is contributed by Sakshi


Javascript




// Javascript code for the above approach
 
function MinOperations(A, N) {
     
    if (N == 1) {
        console.log(0);
        return;
    }
 
    // Calculate the sum of all
    // elements in the array
    let SUM = A.reduce((a, b) => a + b, 0);
 
    // Calculate the average of the array
    let AVG = Math.trunc(SUM / N);
 
    // Calculate the remainder when sum
    // is divided by N
    let REMAINDER = SUM % N;
 
    // Initialize a variable to store the total
    // number of operations
    let ANS = 0;
 
    // Sort the array in ascending order
    A.sort();
 
    // Traverse the largest elements and perform
    // increment operations to minimize the difference
    for (let i = N - 1; i > N - 1 - REMAINDER; i--) {
 
        // Increase the current
        // element to (AVG + 1)
        ANS += Math.abs(A[i] - (AVG + 1));
    }
 
    // Traverse the remaining elements and perform
    // decrement operations to minimize the difference
    for (let i = 0; i <= N - 1 - REMAINDER; i++) {
 
        // Decrease the current element to AVG
        ANS += Math.abs(A[i] - AVG);
    }
 
    // Output half of the total operations
    // since each operation involves increasing
    // one element and decreasing another
    console.log(Math.trunc(ANS / 2));
     
}
 
const arr = [2, 2, 2, 7];
const N = arr.length;
 
//function call
MinOperations(arr, N);
 
// This code is contributed by ragul21


Output

3



















Time Complexity: O(N log N)
Auxiliary Space: O(N)

Approach 2: Stack-Based approach

  • Calculate the sum of all elements in the array (SUM).
  • Calculate the average value of the array elements (AVG) by dividing the sum by the number of elements in the array (N).
  • Calculate the remainder when the sum is divided by N (REMAINDER).
  • Initialize a variable ANS to store the total number of operations required.
  • Sort the array in ascending order.
  • Create an empty stack (operations) to keep track of the operations to be performed.
  • Traverse the largest elements (right end of the sorted array) and push them onto the stack. These elements are candidates for incrementing to minimize the difference.
    • For each element at index i from N – 1 to N – 1 – REMAINDER:
      • Push the difference between the element value and AVG + 1 onto the stack.
  • Traverse the remaining elements (left end of the sorted array) and push them onto the stack. These elements are candidates for decrementing to minimize the difference.
    • For each element at index i from 0 to N – 1 – REMAINDER:
      • Push the difference between the element value and AVG onto the stack.
  • Calculate the total number of operations by popping elements from the stack and adding their absolute values to ANS.
  • Output half of the total operations since each operation involves increasing one element and decreasing another. This is because the operations are paired, and increasing one element by x and decreasing another element by x balances the array.

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
int min_operations_to_balance_array(vector<int>& A) {
    int N = A.size();
    if (N == 1) {
        return 0;
    }
 
    // Calculate the sum of all elements in the array
    long long SUM = accumulate(A.begin(), A.end(), 0ll);
 
    // Calculate the average of the array
    int AVG = SUM / N;
 
    // Calculate the remainder when the sum is divided by N
    int REMAINDER = SUM % N;
 
    // Initialize a variable to store the total number of operations
    int ANS = 0;
 
    // Sort the array in ascending order
    sort(A.begin(), A.end());
 
    // Use a stack to balance the array by performing operations
    stack<int> operations;
 
    // Traverse the largest elements and push them onto the stack
    for (int i = N - 1; i > N - 1 - REMAINDER; i--) {
        operations.push(A[i] - (AVG + 1));
    }
 
    // Traverse the remaining elements and pop elements from the stack
    for (int i = 0; i <= N - 1 - REMAINDER; i++) {
        operations.push(A[i] - AVG);
    }
 
    // Calculate the total number of operations
    while (!operations.empty()) {
        ANS += abs(operations.top());
        operations.pop();
    }
 
    // Output half of the total operations
    // since each operation involves increasing
    // one element and decreasing another
    return ANS / 2;
}
 
int main() {
    vector<int> arr = {2, 2, 2, 7};
 
    // Function Call
    int operations = min_operations_to_balance_array(arr);
    cout << operations << endl;
    return 0;
}


Java




import java.util.*;
public class GFG {
    public static int
    minOperationsToBalanceArray(ArrayList<Integer> A)
    {
        int N = A.size();
        if (N == 1) {
            return 0;
        }
 
        // Calculate the sum of all elements in the array
        long SUM = 0;
        for (int num : A) {
            SUM += num;
        }
 
        // Calculate the average of the array
        int AVG = (int)(SUM / N);
 
        // Calculate the remainder when the sum is divided
        // by N
        int REMAINDER = (int)(SUM % N);
 
        // Initialize a variable to store the total number
        // of operations
        int ANS = 0;
 
        // Sort the array in ascending order
        Collections.sort(A);
 
        // Use a stack to balance the array by performing
        // operations
        Stack<Integer> operations = new Stack<>();
 
        // Traverse the largest elements and push them onto
        // the stack
        for (int i = N - 1; i > N - 1 - REMAINDER; i--) {
            operations.push(A.get(i) - (AVG + 1));
        }
 
        // Traverse the remaining elements and pop elements
        // from the stack
        for (int i = 0; i <= N - 1 - REMAINDER; i++) {
            operations.push(A.get(i) - AVG);
        }
 
        // Calculate the total number of operations
        while (!operations.isEmpty()) {
            ANS += Math.abs(operations.pop());
        }
 
        // Output half of the total operations
        // since each operation involves increasing
        // one element and decreasing another
        return ANS / 2;
    }
 
    public static void main(String[] args)
    {
        ArrayList<Integer> arr
            = new ArrayList<>(Arrays.asList(2, 2, 2, 7));
 
        // Function Call
        int operations = minOperationsToBalanceArray(arr);
        System.out.println(operations);
    }
}


Python3




def min_operations_to_balance_array(arr):
    N = len(arr)
    if N == 1:
        return 0
 
    # Calculate the sum of all elements in the array
    SUM = sum(arr)
 
    # Calculate the average of the array
    AVG = SUM // N
 
    # Calculate the remainder when the sum is divided by N
    REMAINDER = SUM % N
 
    # Initialize a variable to store the total number of operations
    ANS = 0
 
    # Sort the array in ascending order
    arr.sort()
 
    # Use a list to balance the array by performing operations
    operations = []
 
    # Traverse the largest elements and append them to the list
    for i in range(N - 1, N - 1 - REMAINDER, -1):
        operations.append(arr[i] - (AVG + 1))
 
    # Traverse the remaining elements and extend the list
    for i in range(N - 1 - REMAINDER + 1):
        operations.append(arr[i] - AVG)
 
    # Calculate the total number of operations
    ANS = sum(map(abs, operations))
 
    # Output half of the total operations
    # since each operation involves increasing
    # one element and decreasing another
    return ANS // 2
 
# Main function
arr = [2, 2, 2, 7]
operations = min_operations_to_balance_array(arr)
print(operations)


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
class Program
{
    static int MinOperationsToBalanceArray(List<int> A)
    {
        int N = A.Count;
        if (N == 1)
        {
            return 0;
        }
 
        // Calculate the sum of all elements in the array
        long SUM = A.Sum();
 
        // Calculate the average of the array
        int AVG = (int)(SUM / N);
 
        // Calculate the remainder when the sum is divided by N
        int REMAINDER = (int)(SUM % N);
 
        // Initialize a variable to store the total number of operations
        int ANS = 0;
 
        // Sort the array in ascending order
        A.Sort();
 
        // Use a stack to balance the array by performing operations
        Stack<int> operations = new Stack<int>();
 
        // Traverse the largest elements and push them onto the stack
        for (int i = N - 1; i > N - 1 - REMAINDER; i--)
        {
            operations.Push(A[i] - (AVG + 1));
        }
 
        // Traverse the remaining elements and push elements onto the stack
        for (int i = 0; i <= N - 1 - REMAINDER; i++)
        {
            operations.Push(A[i] - AVG);
        }
 
        // Calculate the total number of operations
        while (operations.Count > 0)
        {
            ANS += Math.Abs(operations.Pop());
        }
 
        // Output half of the total operations
        // since each operation involves increasing
        // one element and decreasing another
        return ANS / 2;
    }
 
    static void Main(string[] args)
    {
        List<int> arr = new List<int> { 2, 2, 2, 7 };
 
        // Function Call
        int operations = MinOperationsToBalanceArray(arr);
        Console.WriteLine(operations);
    }
}


Javascript




function minOperationsToBalanceArray(A) {
    const N = A.length;
    if (N === 1) {
        return 0;
    }
 
    // Calculate the sum of all elements in the array
    const SUM = A.reduce((acc, val) => acc + val, 0);
 
    // Calculate the average of the array
    const AVG = Math.floor(SUM / N);
 
    // Calculate the remainder when the sum is divided by N
    const REMAINDER = SUM % N;
 
    // Initialize a variable to store the total number of operations
    let ANS = 0;
 
    // Sort the array in ascending order
    A.sort((a, b) => a - b);
 
    // Use an array to balance the array by performing operations
    const operations = [];
 
    // Traverse the largest elements and push them onto the array
    for (let i = N - 1; i > N - 1 - REMAINDER; i--) {
        operations.push(A[i] - (AVG + 1));
    }
 
    // Traverse the remaining elements and push elements onto the array
    for (let i = 0; i <= N - 1 - REMAINDER; i++) {
        operations.push(A[i] - AVG);
    }
 
    // Calculate the total number of operations
    while (operations.length > 0) {
        ANS += Math.abs(operations.pop());
    }
 
    // Output half of the total operations
    // since each operation involves increasing
    // one element and decreasing another
    return Math.floor(ANS / 2);
}
 
// Test
const arr = [2, 2, 2, 7];
 
// Function Call
const operations = minOperationsToBalanceArray(arr);
console.log(operations);


Output:

3

Time Complexity: O(N * log(N)),Where N is number of elements in an array.

Space Complexity: O(N)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads