Skip to content

Commit 7fc55fe

Browse files
committed
Add solution #3397
1 parent 9b9713f commit 7fc55fe

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -362,6 +362,7 @@
362362
2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy|
363363
2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy|
364364
3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy|
365+
3397|[Maximum Number of Distinct Elements After Operations](./3397-maximum-number-of-distinct-elements-after-operations.js)|Medium|
365366
3402|[Minimum Operations to Make Columns Strictly Increasing](./3402-minimum-operations-to-make-columns-strictly-increasing.js)|Easy|
366367

367368
## License
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* 3397. Maximum Number of Distinct Elements After Operations
3+
* https://leetcode.com/problems/maximum-number-of-distinct-elements-after-operations/
4+
* Difficulty: Medium
5+
*
6+
* You are given an integer array nums and an integer k.
7+
*
8+
* You are allowed to perform the following operation on each element of the array at most once:
9+
* - Add an integer in the range [-k, k] to the element.
10+
*
11+
* Return the maximum possible number of distinct elements in nums after performing the operations.
12+
*/
13+
14+
/**
15+
* @param {number[]} nums
16+
* @param {number} k
17+
* @return {number}
18+
*/
19+
var maxDistinctElements = function(nums, k) {
20+
nums.sort((a, b) => a - b);
21+
let last = nums[0] - k;
22+
let count = 1;
23+
24+
for (let i = 1; i < nums.length; i++) {
25+
if (last + 1 > nums[i] + k) continue;
26+
last = Math.max(last + 1, nums[i] - k);
27+
count++;
28+
}
29+
30+
return count;
31+
};

0 commit comments

Comments
 (0)