3397. Maximum Number of Distinct Elements After Operations #2310
-
|
Topics: You are given an integer array You are allowed to perform the following operation on each element of the array at most once:
Return the maximum possible number of distinct elements in Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to find the maximum number of distinct elements after being allowed to add any integer in the range The key insight is that for each number, we can transform it to any value in the range Approach:
Let's implement this solution in PHP: 3397. Maximum Number of Distinct Elements After Operations <?php
/**
* @param Integer[] $nums
* @param Integer $k
* @return Integer
*/
function maxDistinctElements($nums, $k) {
sort($nums);
$lastAssigned = -PHP_INT_MAX;
$count = 0;
foreach ($nums as $num) {
// Calculate the minimum value we can assign to this element
// It should be at least (lastAssigned + 1) and at least (num - k)
$minCandidate = max($lastAssigned + 1, $num - $k);
// If the minimum candidate is within the allowed range, we can assign it
if ($minCandidate <= $num + $k) {
$lastAssigned = $minCandidate;
$count++;
}
}
return $count;
}
// Test cases
$nums1 = array(1,2,2,3,3,4);
$k1 = 2;
echo "Output 1: " . maxDistinctElements($nums1, $k1) . "\n"; // Expected: 6
$nums2 = array(4,4,4,4);
$k2 = 1;
echo "Output 2: " . maxDistinctElements($nums2, $k2) . "\n"; // Expected: 3
?>Explanation:
Examples:
Complexity:
|
Beta Was this translation helpful? Give feedback.
We need to find the maximum number of distinct elements after being allowed to add any integer in the range
[-k, k]to each element at most once.The key insight is that for each number, we can transform it to any value in the range
[num-k, num+k]. To maximize distinct elements, we should assign the smallest possible distinct value to each number while ensuring it stays within its allowed range.Approach:
[num-k, num+k]