Skip to content

Commit b6a3196

Browse files
authored
Create maximum-number-of-distinct-elements-after-operations.cpp
1 parent 18cd1a3 commit b6a3196

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// Time: O(nlogn)
2+
// Space: O(1)
3+
4+
// sort, greedy
5+
class Solution {
6+
public:
7+
int maxDistinctElements(vector<int>& nums, int k) {
8+
int result = 0;
9+
sort(begin(nums), end(nums));
10+
int curr = numeric_limits<int>::min();
11+
for (const auto& x : nums) {
12+
if (curr > x + k) {
13+
continue;
14+
}
15+
curr = max(curr, x - k) + 1;
16+
++result;
17+
}
18+
return result;
19+
}
20+
};

0 commit comments

Comments
 (0)