Problem
You are given a 0-indexed integer array nums
and an integer value
.
In one operation, you can add or subtract value
from any element of nums
.
- For example, if
nums = [1,2,3]
andvalue = 2
, you can choose to subtractvalue
fromnums[0]
to makenums = [-1,2,3]
.
The MEX (minimum excluded) of an array is the smallest missing non-negative integer in it.
- For example, the MEX of
[-1,2,3]
is0
while the MEX of[1,0,3]
is2
.
Return the maximum MEX ofnums
after applying the mentioned operationany number of times.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= nums.length, value <= 10^5
-109 <= nums[i] <= 10^9
Solution
Method 1 – Remainder Bucketing (Greedy)
Intuition
Since we can add or subtract value
any number of times to any element, each number can be mapped to its remainder modulo value
. For each remainder, the number of unique values we can create is limited by how many times that remainder appears. The maximum MEX is the smallest non-negative integer that cannot be formed by using the available remainders.
Approach
- For each number in
nums
, compute its remainder modulovalue
(make it non-negative). - Count the frequency of each remainder.
- For each integer starting from 0, check if the corresponding remainder bucket has enough elements to form that integer (i.e., for i, check if count[i % value] > i // value).
- The first integer for which this is not true is the answer.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n + M)
, where n = len(nums), M is the answer (at most n + value). - 🧺 Space complexity:
O(value)
for the remainder buckets.