Open In App

Minimum operations for balancing Array difference

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:

Below is the implementation of the above algorithm:




// 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 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




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# 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 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

Below is the implementation of the above approach:




#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;
}




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);
    }
}




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)




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);
    }
}




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)


Article Tags :