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++
// 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
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)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem