VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximize-mex-by-adding-or-subtracting-k-from-array-elements/

⇱ Maximize MEX by adding or subtracting K from Array elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximize MEX by adding or subtracting K from Array elements

Last Updated : 7 Feb, 2026

Given an arr[] of size N and an integer, K, the task is to find the maximum possible value of MEX by adding or subtracting K any number of times from the array elements.

MEX is the minimum non-negative integer that is not present in the array

Examples:

Input: arr[]={1, 3, 4}, K = 2
Output: 2
Explanation: After subtracting K from arr[2] twice,  
the final array will be {1, 3, 0}. 
So the MEX is 2 which is maximum possible answer.

Input: arr[] = {0, 1, 2, 1, 3}, K = 3
Output: 5
Explanation: After adding K to arr[1], the final array will be {0, 4, 2, 1, 3}. 
So the MEX is 5 which is maximum possible answer.

Approach: Follow the below idea to solve the problem:

The maximum MEX which can be achieved from an array of size N is N. For this, we need to have all the elements from 0 to N - 1 by doing some operations.  If there is a number that is not achievable by doing some operation then this is the answer. 

We can generate a number x from a number p by doing addition or subtraction if both remainders are same by diving it with K [i.e., the difference between them is divisible by K].

Follow the steps to solve the problem:

  • Create a map that stores the frequency of the remainder of all the elements of the array.
  • Traverse from 0 to N-1 and check if there is a need to generate the number x then x % K must be present in the map.
    • If it is present in the map then decrease the frequency of x % K and continue.
    • Else, return the number as the answer.

Below is the implementation for the above approach:


Output
5

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

Comment
Article Tags:
Article Tags: