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
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Minimum number of increment-other operations to make all array elements equal.
Next article icon

Make the array elements equal by performing given operations minimum number of times

Last Updated : 21 Apr, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size N, the task is to make all the array elements equal by performing following operations minimum number of times:

  • Increase all array elements of any suffix array by 1.
  • Decrease all the elements of any suffix array by 1.
  • Replace any array element y another.

Examples:

Input: arr[] = {99, 96, 97, 95}
Output: 3
Explanation:
Operation 1: Replace a1  by a2, i.e. 99 ? 96. The array arr[] modifies to {96, 96, 97, 95}.
Operation 2: Increment the suffix { a4} by 2, i.e., 95 ? 97. The array arr[] modifies to {96, 96, 97, 97}.
Operation 3: Decrement the suffix { a3 } by 1, i.e., 97 ? 96. The array arr[] modifies to {96, 96, 96, 96}.
Hence, the total number of operations required is 3.

Input: arr[] = {1, -1, 0, 1, 1}
Output: 2

Approach: The idea is to find the difference between the actual sum and the sum of the array having all elements equal and then choose the operations to perform such that it leads to the minimum count of operations. Follow the steps below to solve the problem:

  • Initialize a variable, say totOps, to store the actual operations needed to make all the array elements equal.
  • Traverse the array and store the difference between all pair of consecutive elements and store their sum in totOps.
  • Initialize a variable, say maxOps, to store the maximum count of operations required.
  • Now, find the maximum change that occurs while changing an element and store it in the maxOps variable. There are three cases:
    • For the 1st element i.e. arr[1], the optimal way to change arr[1] is to make it arr[2].
    • For the last element i.e. arr[N], the optimal way to change arr[N] is to make it into arr[N-1].
    • For the rest of the element, changing arr[i] affects both arr[i-1] and arr[i+1], therefore, the maximum change is abs(arr[i] - arr[i+1]) + abs(arr[i] - arr[i-1]) - abs(arr[i-1] - arr[i+1).
  • Therefore, the minimum operations required is equal to the difference between totOps and maxOps.

Below is the implementation of the above approach:

C++
// C++ Program for the above approach  #include <bits/stdc++.h> using namespace std;  // Function to calculate the minimum // operations of given type required // to make the array elements equal void minOperation(int a[], int N) {     // Stores the total count of operations     int totOps = 0;      // Traverse the array     for (int i = 0; i < N - 1; i++) {          // Update difference between         // pairs of adjacent elements         totOps += abs(a[i] - a[i + 1]);     }      // Store the maximum count of operations     int maxOps         = max(abs(a[0] - a[1]),               abs(a[N - 1] - a[N - 2]));      for (int i = 1; i < N - 1; i++) {          // Rest of the elements         maxOps             = max(maxOps, abs(a[i] - a[i - 1])                               + abs(a[i] - a[i + 1])                               - abs(a[i - 1] - a[i + 1]));     }      // Total Operation - Maximum Operation     cout << totOps - maxOps << endl; }  // Driver Code int main() {     // Given array     int arr[] = { 1, -1, 0, 1, 1 };      // Size of the array     int N = sizeof(arr) / sizeof(arr[0]);      minOperation(arr, N);      return 0; } 
Java
// Java Program for the above approach import java.io.*; class GFG  {    // Function to calculate the minimum   // operations of given type required   // to make the array elements equal   static void minOperation(int a[], int N)   {      // Stores the total count of operations     int totOps = 0;      // Traverse the array     for (int i = 0; i < N - 1; i++)      {        // Update difference between       // pairs of adjacent elements       totOps += Math.abs(a[i] - a[i + 1]);     }      // Store the maximum count of operations     int maxOps       = Math.max(Math.abs(a[0] - a[1]),                  Math.abs(a[N - 1] - a[N - 2]));      for (int i = 1; i < N - 1; i++)      {        // Rest of the elements       maxOps = Math.max(         maxOps,         Math.abs(a[i] - a[i - 1])         + Math.abs(a[i] - a[i + 1])         - Math.abs(a[i - 1] - a[i + 1]));     }      // Total Operation - Maximum Operation     System.out.println(totOps - maxOps);   }    // Driver Code   public static void main(String[] args)   {      // Given array     int[] arr = { 1, -1, 0, 1, 1 };      // Size of the array     int N = arr.length;      minOperation(arr, N);   } }  // This code is contributed by Dharanendra L V 
Python3
# Python3 Program for the above approach  # Function to calculate the minimum # operations of given type required # to make the array elements equal def minOperation(a, N):        # Stores the total count of operations     totOps = 0      # Traverse the array     for i in range(N - 1):          # Update difference between         # pairs of adjacent elements         totOps += abs(a[i] - a[i + 1])      # Store the maximum count of operations     maxOps = max(abs(a[0] - a[1]), abs(a[N - 1] - a[N - 2]))     for i in range(1, N - 1):          # Rest of the elements         maxOps = max(maxOps, abs(a[i] - a[i - 1]) +                       abs(a[i] - a[i + 1])- abs(a[i - 1] - a[i + 1]))      # Total Operation - Maximum Operation     print (totOps - maxOps)  # Driver Code if __name__ == '__main__':        # Given array     arr = [1, -1, 0, 1, 1]      # Size of the array     N = len(arr)     minOperation(arr, N)  # This code is contributed by mohit kumar 29. 
C#
// C# Program for the above approach using System; public class GFG {    // Function to calculate the minimum   // operations of given type required   // to make the array elements equal   static void minOperation(int[] a, int N)   {     // Stores the total count of operations     int totOps = 0;      // Traverse the array     for (int i = 0; i < N - 1; i++)      {        // Update difference between       // pairs of adjacent elements       totOps += Math.Abs(a[i] - a[i + 1]);     }      // Store the maximum count of operations     int maxOps       = Math.Max(Math.Abs(a[0] - a[1]),                  Math.Abs(a[N - 1] - a[N - 2]));      for (int i = 1; i < N - 1; i++)      {        // Rest of the elements       maxOps = Math.Max(         maxOps,         Math.Abs(a[i] - a[i - 1])         + Math.Abs(a[i] - a[i + 1])         - Math.Abs(a[i - 1] - a[i + 1]));     }      // Total Operation - Maximum Operation     Console.WriteLine(totOps - maxOps);   }    // Driver Code   static public void Main()   {      // Given array     int[] arr = { 1, -1, 0, 1, 1 };      // Size of the array     int N = arr.Length;      minOperation(arr, N);   } }  // This code is contributed by Dharanendra L V 
JavaScript
<script> // javascript Program for the above approach      // Function to calculate the minimum     // operations of given type required     // to make the array elements equal     function minOperation(a , N) {          // Stores the total count of operations         var totOps = 0;          // Traverse the array         for (i = 0; i < N - 1; i++) {              // Update difference between             // pairs of adjacent elements             totOps += Math.abs(a[i] - a[i + 1]);         }          // Store the maximum count of operations         var maxOps = Math.max(Math.abs(a[0] - a[1]), Math.abs(a[N - 1] - a[N - 2]));          for (i = 1; i < N - 1; i++) {              // Rest of the elements             maxOps = Math.max(maxOps,                     Math.abs(a[i] - a[i - 1]) + Math.abs(a[i] - a[i + 1]) - Math.abs(a[i - 1] - a[i + 1]));         }          // Total Operation - Maximum Operation         document.write(totOps - maxOps);     }      // Driver Code               // Given array         var arr = [ 1, -1, 0, 1, 1 ];          // Size of the array         var N = arr.length;          minOperation(arr, N);  // This code contributed by aashish1995  </script> 

Output: 
2

 

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


Next Article
Minimum number of increment-other operations to make all array elements equal.

A

atulbelievethat02
Improve
Article Tags :
  • Greedy
  • Sorting
  • Mathematical
  • Data Structures
  • DSA
  • Arrays
  • array-rearrange
Practice Tags :
  • Arrays
  • Data Structures
  • Greedy
  • Mathematical
  • Sorting

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 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 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
  • Maximize the minimum value of Array by performing given operations at most K times
    Given array A[] of size N and integer K, the task for this problem is to maximize the minimum value of the array by performing given operations at most K times. In one operation choose any index and increase that array element by 1. Examples: Input: A[] = {3, 1, 2, 4, 6, 2, 5}, K = 8Output: 4Explana
    10 min read
  • Find the number of operations required to make all array elements Equal
    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 perfo
    6 min read
  • Minimize the number of operations to make all the elements equal with given conditions
    Given an array arr[]. The task is to minimize the number of operations required to make all the elements in arr[] equal. It is allowed to replace any element in arr[] with any other element almost once. Find the minimum number of operations required to do so, in one operation take any suffix of arr[
    7 min read
  • Minimize steps to make Array elements equal by using giving operations
    Given an arr[] of length N. Then the task is to find minimum steps to make all the elements of the given array equal. Two types of operations can be performed as given below: Choose a prefix of size K, where arr[K] = max element in that chosen sub-array and convert all elements equal to max. Choose
    8 min read
  • Minimum Cost to make all array elements equal using given operations
    Given an array arr[] of positive integers and three integers A, R, M, where The cost of adding 1 to an element of the array is A,the cost of subtracting 1 from an element of the array is R andthe cost of adding 1 to an element and subtracting 1 from another element simultaneously is M. The task is t
    12 min read
  • Maximum count of equal numbers in an array after performing given operations
    Given an array of integers. The task is to find the maximum count of equal numbers in an array after applying the given operation any number of times. In an operation: Choose two elements of the array a[i], a[j] (such that i is not equals to j) and, Increase number a[i] by 1 and decrease number a[j]
    5 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
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