Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Minimum operations required to make all the array elements equal
Next article icon

Find the number of operations required to make all array elements Equal

Last Updated : 19 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of N integers, the task is to find the number of operations required to make all elements in the array equal. In one operation we can distribute equal weights from the maximum element to the rest of the array elements. If it is not possible to make the array elements equal after performing the above operations then print -1.

Examples:  

Input: arr[] = [1, 6, 1, 1, 1]; 
Output: 4 
Explanation: Since arr becomes [2, 2, 2, 2, 2] after distribution from max element.

Input : arr[] = [2, 2, 3]; 
Output : -1 
Explanation: Here arr becomes [3, 3, 1] after distribution.  

Algorithm:  

  • Declare temporary variable to store number of times operation is performed.
  • Find maximum element of the given array and store its index value.
  • Check if all the elements are equal to the maximum element after n subtractions.
  • Again check that each element is equal to other elements and return n.

Below is the implementation of above approach:  

C++




// C++ program to find the number
//of operations required to make
//all array elements Equal
#include<bits/stdc++.h>
using namespace std;
 
//Function to find maximum
//element of the given array
int find_n(int a[],int n)
{
        int j = 0, k = 0, s = 0;
 
        int x = *max_element(a, a + n);
        int y = *min_element(a, a + n);
        for (int i = 0; i < n; i++)
        {
            if (a[i] == x)
            {
                s = i;
                break;
            }
 
        }
        for (int i =0;i<n;i++)
        {
            if (a[i] != x && a[i] <= y && a[i] != 0)
            {
                a[j] += 1;
                a[s] -= 1;
                x -= 1;
                k += 1;
                j += 1;
            }
            else if (a[i] != 0)
            {
                j += 1;
            }
        }
 
        for (int i = 0; i < n; i++)
        {
            if (a[i] != x)
            {
                k = -1;
                break;
            }
        }
        return k;
    }
 
// Driver Code
int main()
{
 
    int a[] = {1, 6, 1, 1, 1};
    int n = sizeof(a)/sizeof(a[0]);
    cout << (find_n(a, n));
     
    return 0;
}
 
// This code contributed by princiraj1992
 
 

Java




// Java program to find the number
//of operations required to make
//all array elements Equal
 
import java.util.Arrays;
 
class GFG {
 
//Function to find maximum
//element of the given array
    static int find_n(int[] a) {
        int j = 0, k = 0, s = 0;
 
        int x = Arrays.stream(a).max().getAsInt();
        int y = Arrays.stream(a).min().getAsInt();
        for (int i : a) {
            if (a[i] == x) {
                s = i;
                break;
            }
 
        }
        for (int i : a) {
            if (i != x && i <= y && i != 0) {
                a[j] += 1;
                a[s] -= 1;
                x -= 1;
                k += 1;
                j += 1;
            } else if (i != 0) {
                j += 1;
            }
        }
 
        for (int i : a) {
            if (a[i] != x) {
                k = -1;
                break;
            }
        }
        return k;
    }
//Driver Code
 
    public static void main(String[] args) {
 
        int[] a = {1, 6, 1, 1, 1};
        System.out.println(find_n(a));
    }
 
}
 
 

Python3




# Python program to find the number
# of operations required to make
# all array elements Equal
 
# Function to find maximum
# element of the given array
def find_n(a):
    j, k = 0, 0
     
    x = max(a)
    for i in range(len(a)):
        if(a[i] == x):
            s = i
            break
     
    for i in a:
        if(i != x and i <= min(a) and i !='\0'):
            a[j] += 1
            a[s] -= 1
            x -= 1
            k += 1
            j += 1
        elif(i != '\0'):
            j += 1
             
    for i in range(len(a)):    
        if(a[i] != x):
            k = -1
        break
 
    return k
 
# Driver Code
a = [1, 6, 1, 1, 1]
print (find_n(a))
 
 

C#




// C# program to find the number
// of operations required to make
// all array elements Equal
using System;
using System.Linq;
 
class GFG
{
 
// Function to find maximum
// element of the given array
static int find_n(int []a)
{
    int j = 0, k = 0, s = 0;
 
    int x = a.Max();
    int y = a.Min();
    foreach(int i in a)
    {
        if (a[i] == x)
        {
            s = i;
            break;
        }
 
    }
     
    foreach (int i in a)
    {
        if (i != x && i <= y && i != 0)
        {
            a[j] += 1;
            a[s] -= 1;
            x -= 1;
            k += 1;
            j += 1;
        }
         
        else if (i != 0)
        {
            j += 1;
        }
    }
 
    foreach (int i in a)
    {
        if (a[i] != x)
        {
            k = -1;
            break;
        }
    }
    return k;
}
 
// Driver Code
public static void Main()
{
    int[] a = {1, 6, 1, 1, 1};
    Console.Write(find_n(a));
}
}
 
// This code contributed by 29AjayKumar
 
 

PHP




<?php
// PHP program to find the number of
// operations required to make all
// array elements Equal
 
// Function to find maximum element of
// the given array
function find_n(&$a)
{
    $j = 0;
    $k = 0;
 
    $x = max($a);
    for ($i = 0; $i < sizeof($a); $i++)
    {
        if($a[$i] == $x)
        {
            $s = $i;
            break;
        }
    }
 
    for($i = 0; $i < sizeof($a); $i++)
    {
        if($a[$i] != $x and $a[$i] <= min($a) and
                            $a[$i] !=0)
        {
            $a[$j] += 1;
            $a[$s] -= 1;
            $x -= 1;
            $k += 1;
            $j += 1;
        }
        else if($a[$i] != 0)
            $j += 1;
    }   
 
    for($i = 0; $i < sizeof($a); $i++)
    {
        if($a[$i] != $x)
        {
            $k = -1;
            break;
        }
    }
    return $k;
}
 
// Driver Code
$a = array(1, 6, 1, 1, 1);
echo(find_n($a));
 
// This code is contributed by
// Shivi_Aggarwal
?>
 
 

Javascript




<script>
 
// javascript program to find the number
//of operations required to make
//all array elements Equal
 
 
//Function to find maximum
//element of the given array
function find_n(a) {
    var j = 0, k = 0, s = 0;
 
    var x = Math.max.apply(Math, a);
    var y = Math.min.apply(Math, a);
    for (var i = 0; i < n; i++)
        {
            if (a[i] == x)
            {
                s = i;
                break;
            }
 
        }
        for (var i =0;i<n;i++)
        {
            if (a[i] != x && a[i] <= y && a[i] != 0)
            {
                a[j] += 1;
                a[s] -= 1;
                x -= 1;
                k += 1;
                j += 1;
            }
            else if (a[i] != 0)
            {
                j += 1;
            }
        }
 
        for (var i = 0; i < n; i++)
        {
            if (a[i] != x)
            {
                k = -1;
                break;
            }
        }
        return k;
}
//Driver Code
var a = [1, 6, 1, 1, 1];
var n = a.length;
document.write(find_n(a,n));
 
// This code is contributed by 29AjayKumar
</script>
 
 
Output
4

Complexity Analysis:

  • Time complexity: O(n), where n represents the size of the given array.
  • Auxiliary Space: O(1), no extra space is required, so it is a constant.


Next Article
Minimum operations required to make all the array elements equal

A

AFZAL ANSARI
Improve
Article Tags :
  • Competitive Programming
  • DSA
  • Python
Practice Tags :
  • python

Similar Reads

  • Find the minimum number of operations required to make all array elements equal
    Given an array arr[] of size N. The task is to make all the array elements equal by applying the below operations minimum number of times: Choose a pair of indices (i, j) such that |i - j| = 1 (indices i and j are adjacent) and set arr[i] = arr[i] + |arr[i] - arr[j]|Choose a pair of indices (i, j) s
    6 min read
  • Minimum operations required to make all the array elements equal
    Given an array arr[] of n integer and an integer k. The task is to count the minimum number of times the given operation is required to make all the array elements equal. In a single operation, the kth element of the array is appended at the end of the array and the first element of the array gets d
    6 min read
  • Minimum operations required to make two elements equal in Array
    Given array A[] of size N and integer X, the task is to find the minimum number of operations to make any two elements equal in the array. In one operation choose any element A[i] and replace it with A[i] & X. where & is bitwise AND. If such operations do not exist print -1. Examples: Input:
    9 min read
  • Minimum operations required to make all elements of Array less than equal to 0
    Given an array arr[] consisting of N positive numbers, the task is to find the minimum number of operations required to make all elements of the array less than or equal to 0. In each operation, one has to pick the minimum positive element from the array and subtract all the elements of the array fr
    5 min read
  • Minimum number of operations required to make all elements equal
    Given an array arr[] of length N along with an integer M. All the elements of arr[] are in the range [1, N]. Then your task is to output the minimum number of operations required to make all elements equal given that in one operation you can select at most M elements and increment all of them by 1.
    5 min read
  • Minimum operations required to make all elements in an array of first N odd numbers equal
    Given an array consisting of first N odd numbers, the task is to find the minimum number of operations required to make all the array elements equal by repeatedly selecting a pair and incrementing one element and decrementing the other element in the pair by 1. Examples: Input: N = 3Output: 2Explana
    10 min read
  • Minimum number of increment-other operations to make all array elements equal.
    We are given an array consisting of n elements. At each operation we can select any one element and increase rest of n-1 elements by 1. We have to make all elements equal performing such operation as many times you wish. Find the minimum number of operations needed for this. Examples: Input: arr[] =
    5 min read
  • Minimum operation to make all elements equal in array
    Given an array consisting of n positive integers, the task is to find the minimum number of operations to make all elements equal. In each operation, we can perform addition, multiplication, subtraction, or division with any number and an array element. Examples: Input : arr[] = [1, 2, 3, 4]Output :
    11 min read
  • Minimum no. of operations required to make all Array Elements Zero
    Given an array of N elements and each element is either 1 or 0. You need to make all the elements of the array equal to 0 by performing the below operations: If an element is 1, You can change it's value equal to 0 then, if the next consecutive element is 1, it will automatically get converted to 0.
    12 min read
  • Minimum operations to make all elements equal using the second array
    Given two arrays A[] and B[] both having N elements. Find the minimum number of operations to make all elements of A equal to the second array B. An operation comprises of: A[i] = A[i] - B[i], 0 <= i <= n-1 Note: If it's not possible to make array elements equal print -1.Examples: Input: A[] =
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences