Minimum operations for balancing Array difference
Last Updated :
23 Dec, 2023
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++
#include <bits/stdc++.h>
using namespace std;
void MinOperations(vector< int >& A, int N)
{
if (N == 1) {
cout << 0 << endl;
return ;
}
int SUM = accumulate(A.begin(), A.end(), 0ll);
int AVG = SUM / N;
int REMAINDER = SUM % N;
int ANS = 0;
sort(A.begin(), A.end());
for ( int i = N - 1; i > N - 1 - REMAINDER; i--) {
ANS += abs (A[i] - (AVG + 1));
}
for ( int i = 0; i <= N - 1 - REMAINDER; i++) {
ANS += abs (A[i] - AVG);
}
cout << ANS / 2 << endl;
}
int main()
{
vector< int > arr = { 2, 2, 2, 7 };
int N = 4;
MinOperations(arr, N);
return 0;
}
|
Java
import java.util.Arrays;
public class Main {
public static void minOperations( int [] A, int N) {
if (N == 1 ) {
System.out.println( 0 );
return ;
}
long sum = Arrays.stream(A).asLongStream().sum();
int avg = ( int ) (sum / N);
int remainder = ( int ) (sum % N);
int ans = 0 ;
Arrays.sort(A);
for ( int i = N - 1 ; i > N - 1 - remainder; i--) {
ans += Math.abs(A[i] - (avg + 1 ));
}
for ( int i = 0 ; i <= N - 1 - remainder; i++) {
ans += Math.abs(A[i] - avg);
}
System.out.println(ans / 2 );
}
public static void main(String[] args) {
int [] arr = { 2 , 2 , 2 , 7 };
int N = 4 ;
minOperations(arr, N);
}
}
|
Python
if __name__ = = "__main__":
N = 4
A = [ 2 , 2 , 2 , 7 ]
if N = = 1 :
print ( 0 )
SUM = sum (A)
AVG = SUM / / N
REMAINDER = SUM % N
ANS = 0
A.sort()
for i in range (N - 1 , N - 1 - REMAINDER, - 1 ):
ANS + = abs (A[i] - (AVG + 1 ))
for i in range (N - 1 - REMAINDER + 1 ):
ANS + = abs (A[i] - AVG)
print (ANS / / 2 )
|
C#
using System;
using System.Linq;
public class MainClass
{
public static void MinOperations( int [] A, int N)
{
if (N == 1)
{
Console.WriteLine(0);
return ;
}
long sum = A.Sum();
int avg = ( int )(sum / N);
int remainder = ( int )(sum % N);
int ans = 0;
Array.Sort(A);
for ( int i = N - 1; i > N - 1 - remainder; i--)
{
ans += Math.Abs(A[i] - (avg + 1));
}
for ( int i = 0; i <= N - 1 - remainder; i++)
{
ans += Math.Abs(A[i] - avg);
}
Console.WriteLine(ans / 2);
}
public static void Main( string [] args)
{
int [] arr = { 2, 2, 2, 7 };
int N = 4;
MinOperations(arr, N);
}
}
|
Javascript
function MinOperations(A, N) {
if (N == 1) {
console.log(0);
return ;
}
let SUM = A.reduce((a, b) => a + b, 0);
let AVG = Math.trunc(SUM / N);
let REMAINDER = SUM % N;
let ANS = 0;
A.sort();
for (let i = N - 1; i > N - 1 - REMAINDER; i--) {
ANS += Math.abs(A[i] - (AVG + 1));
}
for (let i = 0; i <= N - 1 - REMAINDER; i++) {
ANS += Math.abs(A[i] - AVG);
}
console.log(Math.trunc(ANS / 2));
}
const arr = [2, 2, 2, 7];
const N = arr.length;
MinOperations(arr, N);
|
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;
}
long long SUM = accumulate(A.begin(), A.end(), 0ll);
int AVG = SUM / N;
int REMAINDER = SUM % N;
int ANS = 0;
sort(A.begin(), A.end());
stack< int > operations;
for ( int i = N - 1; i > N - 1 - REMAINDER; i--) {
operations.push(A[i] - (AVG + 1));
}
for ( int i = 0; i <= N - 1 - REMAINDER; i++) {
operations.push(A[i] - AVG);
}
while (!operations.empty()) {
ANS += abs (operations.top());
operations.pop();
}
return ANS / 2;
}
int main() {
vector< int > arr = {2, 2, 2, 7};
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 ;
}
long SUM = 0 ;
for ( int num : A) {
SUM += num;
}
int AVG = ( int )(SUM / N);
int REMAINDER = ( int )(SUM % N);
int ANS = 0 ;
Collections.sort(A);
Stack<Integer> operations = new Stack<>();
for ( int i = N - 1 ; i > N - 1 - REMAINDER; i--) {
operations.push(A.get(i) - (AVG + 1 ));
}
for ( int i = 0 ; i <= N - 1 - REMAINDER; i++) {
operations.push(A.get(i) - AVG);
}
while (!operations.isEmpty()) {
ANS += Math.abs(operations.pop());
}
return ANS / 2 ;
}
public static void main(String[] args)
{
ArrayList<Integer> arr
= new ArrayList<>(Arrays.asList( 2 , 2 , 2 , 7 ));
int operations = minOperationsToBalanceArray(arr);
System.out.println(operations);
}
}
|
Python3
def min_operations_to_balance_array(arr):
N = len (arr)
if N = = 1 :
return 0
SUM = sum (arr)
AVG = SUM / / N
REMAINDER = SUM % N
ANS = 0
arr.sort()
operations = []
for i in range (N - 1 , N - 1 - REMAINDER, - 1 ):
operations.append(arr[i] - (AVG + 1 ))
for i in range (N - 1 - REMAINDER + 1 ):
operations.append(arr[i] - AVG)
ANS = sum ( map ( abs , operations))
return ANS / / 2
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;
}
long SUM = A.Sum();
int AVG = ( int )(SUM / N);
int REMAINDER = ( int )(SUM % N);
int ANS = 0;
A.Sort();
Stack< int > operations = new Stack< int >();
for ( int i = N - 1; i > N - 1 - REMAINDER; i--)
{
operations.Push(A[i] - (AVG + 1));
}
for ( int i = 0; i <= N - 1 - REMAINDER; i++)
{
operations.Push(A[i] - AVG);
}
while (operations.Count > 0)
{
ANS += Math.Abs(operations.Pop());
}
return ANS / 2;
}
static void Main( string [] args)
{
List< int > arr = new List< int > { 2, 2, 2, 7 };
int operations = MinOperationsToBalanceArray(arr);
Console.WriteLine(operations);
}
}
|
Javascript
function minOperationsToBalanceArray(A) {
const N = A.length;
if (N === 1) {
return 0;
}
const SUM = A.reduce((acc, val) => acc + val, 0);
const AVG = Math.floor(SUM / N);
const REMAINDER = SUM % N;
let ANS = 0;
A.sort((a, b) => a - b);
const operations = [];
for (let i = N - 1; i > N - 1 - REMAINDER; i--) {
operations.push(A[i] - (AVG + 1));
}
for (let i = 0; i <= N - 1 - REMAINDER; i++) {
operations.push(A[i] - AVG);
}
while (operations.length > 0) {
ANS += Math.abs(operations.pop());
}
return Math.floor(ANS / 2);
}
const arr = [2, 2, 2, 7];
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)
Share your thoughts in the comments
Please Login to comment...