Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Maximize the minimum element and return it
Next article icon

Maximize minimum element of an Array using operations

Last Updated : 31 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array A[] of N integers and two integers X and Y (X ≤ Y), the task is to find the maximum possible value of the minimum element in an array A[] of N integers by adding X to one element and subtracting Y from another element any number of times, where X ≤ Y.

Examples:

Input: N= 3, A[] = {1, 5, 9}, X = 2, Y = 2
Output: 5
Explanation: We will perform the operation twice as follows:

  • Add X to first element and subtract Y from third element. Array becomes - {3, 5, 7}
  • Again, add X to first element and subtract Y from third element. Array becomes - {5, 5, 5}

The minimum element is 5. It can be checked that after performing operation with any other indices or any more number of times, the minimum element cannot be made greater than 5.

Input: N = 3, A[] = {11, 1, 2}, X = 2, Y = 3
Output: 3
Explanation: We will perform the operation twice as follows:

  • Add X to second element and subtract Y from first element. Array becomes - {8, 3, 2}
  • Add X to third element and subtract Y from first element. Array becomes - {5, 3, 4}

The minimum element is 3. It can be checked that after performing operation with any other indices or any more number of times, the minimum element cannot be made greater than 3.

Approach: To solve the problem follow the below idea:

The idea is to use binary search. Initialize two variables lo and hi to the minimum and maximum element of the array, respectively. Now, calculate mid value between lo and hi using binary search. Iterate the array to count the number of additions and subtractions required to make all elements either greater than or equal to mid, using X and Y respectively. If the total number of subtractions required is greater than or equal to the total number of additions required, the update lo=mid and continues the binary search, else update hi=mid-1 and continue the search. When lo and hi become equal, return this value as the answer.

Below are the steps for the above approach:

  • Initialize the lower bound (say "lo") and upper bound(say "hi") for binary search with minimum and maximum elements of the array respectively.
  • In each iteration of the binary search, initialize two variables, say "add" and "subtract" with 0.
  • Iterate through the array.
  • If the current element of the array is greater than or equal to mid, add (A[i]-mid)/Y to "subtract".
  • Else, add (mid-A[i]+X-1)/X to "add".
  • If "subtract" is greater than or equal to "add", set lo=mid.
  • Else, set hi=mid-1.
  • When lo becomes greater than or equal to hi, return lo.

Below is the code for the above approach:

C++
// C++ code for the above approach #include <bits/stdc++.h> using namespace std; #define int long long  // Function to Maximize the minimum element // of array by adding and subtracting X and // Y from distinct elements any number // of times int maximizeMinimumElement(int N, int A[], int X, int Y) {      // Initializing lo and hi     int lo = *min_element(A, A + N);     int hi = *max_element(A, A + N);      while (lo < hi) {          // Initializing mid, add and         // subtract         int mid = lo + (hi - lo + 1) / 2;         int add = 0, subtract = 0;          // Iterating through the array         for (int i = 0; i < N; i++) {              // If mid is less than or equal             // to A[i], accordingly increase             // the value of subtract             if (mid <= A[i]) {                 subtract += (A[i] - mid) / Y;             }              // Else, accordingly increase             // the value of add             else {                 add += (mid - A[i] + X - 1) / X;             }         }          // If subtract is greater than or         // equal to add, set lo = mid         if (subtract >= add) {             lo = mid;         }          // Else set hi = mid-1         else {             hi = mid - 1;         }     }      // Return the answer     return lo; }  // Driver code int32_t main() {     int N = 3, X = 2, Y = 2;     int A[] = { 1, 5, 9 };      // Function Call     cout << maximizeMinimumElement(N, A, X, Y);     return 0; } 
Java
// Java code for the above approach import java.util.*;  class GFG {      // Function to Maximize the minimum element     // of array by adding and subtracting X and     // Y from distinct elements any number     // of times     public static int maximizeMinimumElement(int N, int A[],                                              int X, int Y)     {          // Initializing lo and hi         int lo = Arrays.stream(A).min().getAsInt();         int hi = Arrays.stream(A).max().getAsInt();          while (lo < hi) {              // Initializing mid, add and             // subtract             int mid = lo + (hi - lo + 1) / 2;             int add = 0, subtract = 0;              // Iterating through the array             for (int i = 0; i < N; i++) {                  // If mid is less than or equal                 // to A[i], accordingly increase                 // the value of subtract                 if (mid <= A[i]) {                     subtract += (A[i] - mid) / Y;                 }                  // Else, accordingly increase                 // the value of add                 else {                     add += (mid - A[i] + X - 1) / X;                 }             }              // If subtract is greater than or             // equal to add, set lo = mid             if (subtract >= add) {                 lo = mid;             }              // Else set hi = mid-1             else {                 hi = mid - 1;             }         }          // Return the answer         return lo;     }      // Driver code     public static void main(String[] args)     {         int N = 3, X = 2, Y = 2;         int A[] = { 1, 5, 9 };          // Function Call         System.out.println(             maximizeMinimumElement(N, A, X, Y));     } } // This code is contributed by prasad264 
Python3
def maximizeMinimumElement(N, A, X, Y):     # Initializing lo and hi     lo = min(A)     hi = max(A)      while lo < hi:         # Initializing mid, add and subtract         mid = lo + (hi - lo + 1) // 2         add = 0         subtract = 0          # Iterating through the array         for i in range(N):             # If mid is less than or equal to A[i],              # accordingly increase the value of subtract             if mid <= A[i]:                 subtract += (A[i] - mid) // Y             # Else, accordingly increase the value of add             else:                 add += (mid - A[i] + X - 1) // X          # If subtract is greater than or equal to add, set lo = mid         if subtract >= add:             lo = mid         # Else set hi = mid-1         else:             hi = mid - 1      # Return the answer     return lo  # Driver code N = 3 X = 2 Y = 2 A = [1, 5, 9]  # Function Call print(maximizeMinimumElement(N, A, X, Y)) 
C#
using System;  class GFG {     static int MaximizeMinimumElement(int N, int[] A, int X, int Y)     {         // Initializing lo and hi         int lo = A[0];         int hi = A[0];                  // Find the minimum and maximum values in the array         for (int i = 1; i < N; i++)         {             lo = Math.Min(lo, A[i]);             hi = Math.Max(hi, A[i]);         }          while (lo < hi)         {             // Initializing mid, add and subtract             int mid = lo + (hi - lo + 1) / 2;             int add = 0;             int subtract = 0;              // Iterating through the array             for (int i = 0; i < N; i++)             {                 // If mid is less than or equal to A[i],                 // accordingly increase the value of subtract                 if (mid <= A[i])                 {                     subtract += (A[i] - mid) / Y;                 }                 // Else, accordingly increase the value of add                 else                 {                     add += (mid - A[i] + X - 1) / X;                 }             }              // If subtract is greater than or equal to add, set lo = mid             if (subtract >= add)             {                 lo = mid;             }             // Else set hi = mid-1             else             {                 hi = mid - 1;             }         }          // Return the answer         return lo;     }      static void Main(string[] args)     {         int N = 3;         int X = 2;         int Y = 2;         int[] A = new int[] { 1, 5, 9 };          // Function Call         Console.WriteLine(MaximizeMinimumElement(N, A, X, Y));     } } 
JavaScript
// JavaScript code for the above approach  // Function to maximize the minimum element  // of an array by adding and subtracting X and  // Y from distinct elements any number of times function maximizeMinimumElement(N, A, X, Y) {          // Initializing lo and hi     let lo = Math.min(...A);     let hi = Math.max(...A);      while (lo < hi) {         // Initializing mid, add and          // subtract         let mid = lo + Math.floor((hi - lo + 1) / 2);         let add = 0;         let subtract = 0;          // Iterating through the array         for (let i = 0; i < N; i++) {             // If mid is less than or equal              // to A[i], accordingly increase              // the value of subtract             if (mid <= A[i]) {                 subtract += Math.floor((A[i] - mid) / Y);             }                          // Else, accordingly increase              // the value of add             else {                 add += Math.floor((mid - A[i] + X - 1) / X);             }         }          // If subtract is greater than or          // equal to add, set lo = mid         if (subtract >= add) {             lo = mid;         }                  // Else set hi = mid-1         else {             hi = mid - 1;         }     }      // Return the answer     return lo; }  // Driver code let N = 3; let X = 2; let Y = 2; let A = [1, 5, 9];  // Function call console.log(maximizeMinimumElement(N, A, X, Y)); 

Output
5

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


Next Article
Maximize the minimum element and return it

K

kamabokogonpachiro
Improve
Article Tags :
  • Searching
  • DSA
  • Arrays
  • Binary Search
Practice Tags :
  • Arrays
  • Binary Search
  • Searching

Similar Reads

    Binary Search on Answer Tutorial with Problems
    Binary Search on Answer is the algorithm in which we are finding our answer with the help of some particular conditions. We have given a search space in which we take an element [mid] and check its validity as our answer, if it satisfies our given condition in the problem then we store its value and
    15+ min read
    Time Crunch Challenge
    Geeks for Geeks is organizing a hackathon consisting of N sections, each containing K questions. The duration of the hackathon is H hours. Each participant can determine their speed of solving questions, denoted as S (S = questions-per-hour). During each hour, a participant can choose a section and
    10 min read
    Find minimum subarray length to reduce frequency
    Given an array arr[] of length N and a positive integer k, the task is to find the minimum length of the subarray that needs to be removed from the given array such that the frequency of the remaining elements in the array is less than or equal to k. Examples: Input: n = 4, arr[] = {3, 1, 3, 6}, k =
    10 min read
    Maximize minimum sweetness in cake cutting
    Given that cake consists of N chunks, whose individual sweetness is represented by the sweetness[] array, the task is to cut the cake into K + 1 pieces to maximize the minimum sweetness. Examples: Input: N = 6, K = 2, sweetness[] = {6, 3, 2, 8, 7, 5}Output: 9Explanation: Divide the cake into [6, 3],
    7 min read
    Maximize minimum element of an Array using operations
    Given an array A[] of N integers and two integers X and Y (X ≤ Y), the task is to find the maximum possible value of the minimum element in an array A[] of N integers by adding X to one element and subtracting Y from another element any number of times, where X ≤ Y. Examples: Input: N= 3, A[] = {1,
    8 min read
    Maximize the minimum element and return it
    Given an array A[] of size N along with W, K. We can increase W continuous elements by 1 where we are allowed to perform this operation K times, the task is to maximize the minimum element and return the minimum element after operations. Examples: Input: N = 6, K = 2, W = 3, A[] = {2, 2, 2, 2, 1, 1}
    8 min read
    Find the maximum value of the K-th smallest usage value in Array
    Given an array arr[] of size N and with integers M, K. You are allowed to perform an operation where you can increase the value of the least element of the array by 1. You are to do this M times. The task is to find the largest possible value for the Kth smallest value among arr[] after M operations
    7 min read
    Aggressive Cows
    Given an array stalls[] which denotes the position of a stall and an integer k which denotes the number of aggressive cows. The task is to assign stalls to k cows such that the minimum distance between any two of them is the maximum possible.Examples: Input: stalls[] = [1, 2, 4, 8, 9], k = 3Output:
    15+ min read
    Minimum time to complete at least K tasks when everyone rest after each task
    Given an array arr[] of size n representing the time taken by a person to complete a task. Also, an array restTime[] which denotes the amount of time one person takes to rest after finishing a task. Each person is independent of others i.e. they can work simultaneously on different tasks at the same
    8 min read
    Maximum count of integers to be chosen from given two stacks having sum at most K
    Given two stacks stack1[] and stack2[] of size N and M respectively and an integer K, The task is to count the maximum number of integers from two stacks having sum less than or equal to K. Examples: Input: stack1[ ] = { 60, 90, 120 }stack2[ ] = { 100, 10, 10, 250 }, K = 130Output: 3Explanation: Tak
    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