Skip to content

Commit 698892b

Browse files
committed
feat: add solutions to lc problem: No.3397
1 parent b9568fa commit 698892b

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed

solution/3300-3399/3397.Maximum Number of Distinct Elements After Operations/README.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,28 @@ function maxDistinctElements(nums: number[], k: number): number {
176176
}
177177
```
178178

179+
#### Rust
180+
181+
```rust
182+
impl Solution {
183+
pub fn max_distinct_elements(mut nums: Vec<i32>, k: i32) -> i32 {
184+
nums.sort();
185+
let mut ans = 0;
186+
let mut pre = i32::MIN;
187+
188+
for &x in &nums {
189+
let cur = (x + k).min((x - k).max(pre + 1));
190+
if cur > pre {
191+
ans += 1;
192+
pre = cur;
193+
}
194+
}
195+
196+
ans
197+
}
198+
}
199+
```
200+
179201
<!-- tabs:end -->
180202

181203
<!-- solution:end -->

solution/3300-3399/3397.Maximum Number of Distinct Elements After Operations/README_EN.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,28 @@ function maxDistinctElements(nums: number[], k: number): number {
174174
}
175175
```
176176

177+
#### Rust
178+
179+
```rust
180+
impl Solution {
181+
pub fn max_distinct_elements(mut nums: Vec<i32>, k: i32) -> i32 {
182+
nums.sort();
183+
let mut ans = 0;
184+
let mut pre = i32::MIN;
185+
186+
for &x in &nums {
187+
let cur = (x + k).min((x - k).max(pre + 1));
188+
if cur > pre {
189+
ans += 1;
190+
pre = cur;
191+
}
192+
}
193+
194+
ans
195+
}
196+
}
197+
```
198+
177199
<!-- tabs:end -->
178200

179201
<!-- solution:end -->
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
impl Solution {
2+
pub fn max_distinct_elements(mut nums: Vec<i32>, k: i32) -> i32 {
3+
nums.sort();
4+
let mut ans = 0;
5+
let mut pre = i32::MIN;
6+
7+
for &x in &nums {
8+
let cur = (x + k).min((x - k).max(pre + 1));
9+
if cur > pre {
10+
ans += 1;
11+
pre = cur;
12+
}
13+
}
14+
15+
ans
16+
}
17+
}

0 commit comments

Comments
 (0)