3397. Maximum Number of Distinct Elements After Operations
UnknownView on LeetCode
Time: O(n log n)
Space: O(1)
Problem Overview
Maximum Number of Distinct Elements After Operations (Unknown) asks you to solve a structured algorithmic task. This is a common Array / Greedy pattern in coding interviews. Sort; greedy assign each element the smallest available value ≥ nums[i]-k.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Sort; greedy assign each element the smallest available value ≥ nums[i]-k.
3397.cs
C#
// Approach: Sort; greedy assign each element the smallest available value ≥ nums[i]-k.
// Time: O(n log n) Space: O(1)
public class Solution
{
public int MaxDistinctElements(int[] nums, int k)
{
Array.Sort(nums);
int n = nums.Length;
int distinctCount = 0;
int previousValue = int.MinValue;
foreach (int currentNum in nums)
{
int optimalValue = Math.Min(currentNum + k, Math.Max(currentNum - k, previousValue + 1));
if (optimalValue > previousValue)
{
distinctCount++;
previousValue = optimalValue;
}
}
return distinctCount;
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)
- 26. Remove Duplicates from Sorted Array(Easy)
- 27. Remove Element(Easy)