-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path18_Maximum_Number_of_Distinct_Elements_After_Operations.cpp
More file actions
69 lines (50 loc) · 1.38 KB
/
Copy path18_Maximum_Number_of_Distinct_Elements_After_Operations.cpp
File metadata and controls
69 lines (50 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// 3397. Maximum Number of Distinct Elements After Operations
// Medium
// Topics
// premium lock icon
// Companies
// Hint
// 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 <= 105
// 1 <= nums[i] <= 109
// 0 <= k <= 109
class Solution
{
public:
int maxDistinctElements(vector<int> &nums, int k)
{
if (nums.empty())
return 0;
sort(nums.begin(), nums.end());
int count = 0;
int prev = INT_MIN >> 1;
for (int a : nums)
{
int low = a - k;
int high = a + k;
int x = prev + 1;
if (x < low)
x = low;
if (x <= high)
{
count++;
prev = x;
}
}
return count;
}
};