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 cost required to rearrange a given array to make it equal to another given array
Next article icon

Minimum increments to make all array elements equal with sum same as the given array after exactly one removal

Last Updated : 16 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size N and an integer K, the task is to check if all array elements can be made equal by removing an array element and incrementing the value of all other array elements such that the total sum of the array elements remains the same. If found to be true, then print "YES". Otherwise, print "NO".

Examples :

Input: arr[] = { 2, 2, 2, 3 } 
Output: YES 
Explanation: 
Removing arr[2] ( 0-based indexing ) from the array and incrementing all other elements by 1 modifies arr[] to { 3, 3, 3 } 
Since all array elements are equal. Therefore, the required output is "YES".

Input: arr[] = { 0, 3, 0 }, K = 3 
Output:: NO 
Removing arr[1] ( 0-based indexing ) from the array and incrementing the value arr[0] by 1 and arr[2] by 2 modifies arr[] to { 1, 2 } 
Since all array elements are not equal. Therefore, the required output is "NO".

Approach: The problem can be solved using Greedy technique. The idea is to remove the largest array element and increment the value of other elements such that the total sum remains same. Follow the steps below to solve the problem:

  • Initialize a variable, say secMax, to store the second largest element of the array.
  • Initialize a variable, say totalSum, to store the sum of the array elements.
  • Traverse the array and calculate the sum of the array elements and find the second largest array element.
  • If totalSum < (N - 1) * secMax or totalSum % (N - 1) != 0, then print "NO".
  • Otherwise, print "YES".

Below is the implementation of above approach

C++
// C++ program to implement // the above approach  #include <bits/stdc++.h> using namespace std;  // Function to check if an array of // equal elements with sum equal to // the given array can be obtained or not bool CheckAllarrayEqual(int arr[], int N) {     // Base case     if (N == 1) {         return true;     }      // Stores sum of     // array elements     int totalSum = arr[0];      // Stores second largest     // array element     int secMax = INT_MIN;      // Stores the largest     // array element     int Max = arr[0];      // Traverse the array     for (int i = 1; i < N; i++) {          if (arr[i] >= Max) {              // Update secMax             secMax = Max;              // Update Max             Max = arr[i];         }         else if (arr[i] > secMax) {              // Update secMax             secMax = arr[i];         }          // Update totalSum         totalSum += arr[i];     }      // If totalSum is less than     // secMax * (N - 1))     // or totalSum is not     // divisible by (N - 1)     if (((secMax * (N - 1)) > totalSum) or (totalSum % (N - 1))) {         return false;     }      return true; }  // Driver Code int main() {     int arr[] = { 6, 2, 2, 2 };     int N = sizeof(arr) / sizeof(arr[0]);      if (CheckAllarrayEqual(arr, N)) {         cout << "YES";     }     else {         cout << "NO";     } } 
Java
// Java program to implement // the above approach import java.util.*;     class GFG{  // Function to check if an array of // equal elements with sum equal to // the given array can be obtained or not static boolean CheckAllarrayEqual(int[] arr,                                   int N) {          // Base case     if (N == 1)     {         return true;     }        // Stores sum of     // array elements     int totalSum = arr[0];        // Stores second largest     // array element     int secMax = Integer.MIN_VALUE;        // Stores the largest     // array element     int Max = arr[0];        // Traverse the array     for(int i = 1; i < N; i++)     {         if (arr[i] >= Max)         {                          // Update secMax             secMax = Max;                          // Update Max             Max = arr[i];         }         else if (arr[i] > secMax)         {                          // Update secMax             secMax = arr[i];         }                  // Update totalSum         totalSum += arr[i];     }        // If totalSum is less than     // secMax * (N - 1))     // or totalSum is not     // divisible by (N - 1)     if (((secMax * (N - 1)) > totalSum) || (totalSum % (N - 1) != 0))     {         return false;     }       return true; }     // Driver Code public static void main(String[] args) {     int[] arr = { 6, 2, 2, 2 };     int N = arr.length;        if (CheckAllarrayEqual(arr, N))     {         System.out.print("YES");     }     else      {         System.out.print("NO");     } } }  // This code is contributed by susmitakundugoaldanga 
Python3
# Python3 program to implement # the above approach  # Function to check if an array of # equal elements with sum equal to # the given array can be obtained or not def CheckAllarrayEqual(arr, N):          # Base case     if (N == 1):         return True      # Stores sum of     # array elements     totalSum = arr[0]      # Stores second largest     # array element     secMax = -10**19      # Stores the largest     # array element     Max = arr[0]      # Traverse the array     for i in range(1,N):          if (arr[i] >= Max):              # Update secMax             secMax = Max              # Update Max             Max = arr[i]         elif (arr[i] > secMax):              # Update secMax             secMax = arr[i]          # Update totalSum         totalSum += arr[i]      # If totalSum is less than     # secMax * (N - 1))     # or totalSum is not     # divisible by (N - 1)     if (((secMax * (N - 1)) > totalSum) or (totalSum % (N - 1))):         return False     return True  # Driver Code if __name__ == '__main__':     arr=[6, 2, 2, 2]     N = len(arr)      if (CheckAllarrayEqual(arr, N)):         print("YES")     else:         print("NO")          # This code is contributed by mohit kumar 29 
C#
// C# program to implement // the above approach   using System; class GFG {   // Function to check if an array of // equal elements with sum equal to // the given array can be obtained or not static bool CheckAllarrayEqual(int[] arr, int N) {     // Base case     if (N == 1) {         return true;     }       // Stores sum of     // array elements     int totalSum = arr[0];       // Stores second largest     // array element     int secMax = Int32.MinValue;       // Stores the largest     // array element     int Max = arr[0];       // Traverse the array     for (int i = 1; i < N; i++) {           if (arr[i] >= Max) {               // Update secMax             secMax = Max;               // Update Max             Max = arr[i];         }         else if (arr[i] > secMax) {               // Update secMax             secMax = arr[i];         }           // Update totalSum         totalSum += arr[i];     }       // If totalSum is less than     // secMax * (N - 1))     // or totalSum is not     // divisible by (N - 1)     if (((secMax * (N - 1)) > totalSum) || (totalSum % (N - 1) != 0)) {         return false;     }       return true; }   // Driver Code public static void Main() {     int[] arr = { 6, 2, 2, 2 };     int N = arr.Length;       if (CheckAllarrayEqual(arr, N)) {         Console.Write("YES");     }     else {         Console.Write("NO");     } } }  // This code is contributed by sanjoy_62 
JavaScript
<script>  // JavaScript program to implement // the above approach   // Function to check if an array of // equal elements with sum equal to // the given array can be obtained or not function CheckAllarrayEqual(arr,N) {          // Base case     if (N == 1)     {         return true;     }      // Stores sum of     // array elements     let totalSum = arr[0];      // Stores second largest     // array element     let secMax = Number.MIN_VALUE;      // Stores the largest     // array element     let Max = arr[0];      // Traverse the array     for(let i = 1; i < N; i++)     {         if (arr[i] >= Max)         {                          // Update secMax             secMax = Max;                          // Update Max             Max = arr[i];         }         else if (arr[i] > secMax)         {                          // Update secMax             secMax = arr[i];         }                  // Update totalSum         totalSum += arr[i];     }      // If totalSum is less than     // secMax * (N - 1))     // or totalSum is not     // divisible by (N - 1)     if (((secMax * (N - 1)) > totalSum) || (totalSum % (N - 1) != 0))     {         return false;     }      return true; }      // Driver Code      let arr = [ 6, 2, 2, 2 ];     let N = arr.length;      if (CheckAllarrayEqual(arr, N))     {         document.write("YES");     }     else     {         document.write("NO");     }   // This code is contributed by sravan kumar Gottumukkala  </script> 

Output: 
YES

 

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


Next Article
Minimum cost required to rearrange a given array to make it equal to another given array

V

varuntak22
Improve
Article Tags :
  • Misc
  • Greedy
  • DSA
  • Arrays
  • Arrays
  • Greedy Algorithms
Practice Tags :
  • Arrays
  • Arrays
  • Greedy
  • Misc

Similar Reads

  • Minimum increments or decrements by 1 required to make all array elements in AP
    Given an array arr[] consisting of N integers, the task is to find the minimum number of increment/decrement by 1 required to be performed on array elements to make all the elements of the given array arr[] in AP. If it is not possible to make the array in AP, then print "-1". Examples: Input: arr[]
    11 min read
  • Minimum increments to modify array such that value of any array element can be splitted to make all remaining elements equal
    Given an array arr[] consisting of N elements, the task is to find the minimum number of increments required to be performed on the given array such that after selecting any array element at any index and splitting its value to the other array elements makes all other N - 1 elements equal. Examples:
    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
  • Maximum array elements that can be removed along with its adjacent values to empty given array
    Given an array arr[] of size N. In each operation, pick an array element X and remove all array elements in the range [X - 1, X + 1]. The task is to find the maximum number of steps required such that no coins left in the array. Examples: Input: coins [] = {5, 1, 3, 2, 6, 7, 4} Output: 4 Explanation
    7 min read
  • Minimum cost required to rearrange a given array to make it equal to another given array
    Given two arrays A[] and B[] consisting of M and N integers respectively, and an integer C, the task is to find the minimum cost required to make the sequence A exactly the same as B(consists of distinct elements only) by performing the following operations on array A[]: Remove any element from the
    12 min read
  • Minimum sum of values subtracted from array elements to make all array elements equal
    Given an array arr[] consisting of N positive integers, the task is to find the sum of all the array elements required to be subtracted from each array element such that remaining array elements are all equal. Examples: Input: arr[] = {1, 2}Output: 1Explanation: Subtracting 1 from arr[1] modifies ar
    4 min read
  • Minimum removals required to make frequency of all remaining array elements equal
    Given an array arr[] of size N, the task is to find the minimum number of array elements required to be removed such that the frequency of the remaining array elements become equal. Examples : Input: arr[] = {2, 4, 3, 2, 5, 3}Output: 2Explanation: Following two possibilities exists:1) Either remove
    13 min read
  • Minimum removals required to make frequency of each array element equal to its value
    Given an array arr[] of size N, the task is to find the minimum count of array elements required to be removed such that frequency of each array element is equal to its value Examples: Input: arr[] = { 2, 4, 1, 4, 2 } Output: 2 Explanation: Removing arr[1] from the array modifies arr[] to { 2, 1, 4,
    11 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
  • Make all array elements equal by reducing array elements to half minimum number of times
    Given an array arr[] consisting of N integers, the task is to minimize the number of operations required to make all array elements equal by converting Ai to Ai / 2. in each operation Examples: Input: arr[] = {3, 1, 1, 3}Output: 2Explanation: Reducing A0 to A0 / 2 modifies arr[] to {1, 1, 1, 3}. Red
    6 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