DDSA Solutions

3397. Maximum Number of Distinct Elements After Operations

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.

Related patterns: Array, Greedy, Sorting

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