[LeetCode] Maximum Number of Distinct Elements After Operations

3397. Maximum Number of Distinct Elements After Operations

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int maxDistinctElements(vector<int>& nums, int k) {
sort(begin(nums), end(nums));
int res = 0;
for(int i = 0; i < nums.size(); i++) {
int mi = nums[i] * 1ll - k, ma = nums[i] * 1ll + k;
if(i) {
if(nums[i-1] < mi) nums[i] = mi;
else nums[i] = min(ma, nums[i-1] + 1);
} else nums[i] = mi;

if(!i or nums[i] != nums[i-1]) res++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/12/22/PS/LeetCode/maximum-number-of-distinct-elements-after-operations/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.