Maximum Number of Distinct Elements After Operations Problem
Description
LeetCode Problem 3397.
You are given an integer array nums and an integer k.
You are allowed to perform the following operation on each element of the array at most once:
- Add an integer in the range
[-k, k]to the element.
Return the maximum possible number of distinct elements in nums after performing the operations.
Example 1:
Input: nums = [1,2,2,3,3,4], k = 2
Output: 6
Explanation:
nums changes to [-1, 0, 1, 2, 3, 4] after performing operations on the first four elements.
Example 2:
Input: nums = [4,4,4,4], k = 1
Output: 3
Explanation:
By adding -1 to nums[0] and 1 to nums[1], nums changes to [3, 5, 4, 4].
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^90 <= k <= 10^9
Solution
Approach: Greedy + Sorting
Sort nums and process the numbers from smallest to largest. Keep pre, the largest value already assigned (initially negative infinity).
For each x, we want the smallest value in [x - k, x + k] that is greater than pre, because a small value leaves the most room for the numbers that follow. That value is min(x + k, max(x - k, pre + 1)). If it is greater than pre, it is a new distinct value: count it and set pre to it. Otherwise x has to repeat an earlier value and is not counted.
Complexity: O(n log n) time for the sort, O(log n) extra space.
from math import inf
class Solution:
def maxDistinctElements(self, nums: List[int], k: int) -> int:
nums.sort()
ans = 0
pre = -inf
for x in nums:
cur = min(x + k, max(x - k, pre + 1))
if cur > pre:
ans += 1
pre = cur
return ans