Maximum Number of Distinct Elements After Operations - Greedy w/ Sorting [JS, Java]

Description 

Solution: Greedy w/ Sorting

Sort nums in asc order.
The largest range is achieved by reducing the minimum element of nums by k.
Keep track of the current largest element we have operated on and change each nums[i] to take the next available spot within the bounds of k.

  • If it's impossible to change nums[i] into a distinct number (last + 1 >= nums[i] + k), skip it.
  • Otherwise, take the smallest possible next position: Math.max(last + 1, nums[i] - k).
    Return the number of distinct elements after the operations.

Time Complexity: O(n log(n))
Space Complexity: O(log(n))

JS

function maxDistinctElements(nums, k) {
  nums.sort((a, b) => a - b);
  let last = nums[0] - k, distinct = 1;
  for (let i = 1; i < nums.length; i++) {
    if (last + 1 > nums[i] + k) continue;
    last = Math.max(last + 1, nums[i] - k);
    distinct++;
  }
  return distinct;
};

Java

class Solution {
    public int maxDistinctElements(int[] nums, int k) {
        Arrays.sort(nums);
        int last = nums[0] - k;
        int distinct = 1;
        for (int i = 1; i < nums.length; i++) {
            if (last + 1 > nums[i] + k) continue;
            last = Math.max(last + 1, nums[i] - k);
            distinct++;
        }
        return distinct;
    }
}

Comments

Popular posts from this blog

Beautiful Towers II - Monotonic Increasing Stack [JS]

Minimum Number of Operations to Sort a Binary Tree by Level - BFS & Cycle Counting Explained [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Maximum Score After Applying Operations on a Tree - DFS [JS]

Divide Nodes Into the Maximum Number of Groups - Union Find & BFS [JS]