LeetCode 3397: Maximum Number of Distinct Elements After Operations Solution

Master LeetCode problem 3397 (Maximum Number of Distinct Elements After Operations), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

3397. Maximum Number of Distinct Elements After Operations

Problem Explanation

Explanation

To maximize the number of distinct elements, we can perform the following steps:

  1. Count the frequency of each number in the array.
  2. Sort the numbers based on their frequencies in non-increasing order.
  3. For each number, if it has a frequency greater than 1, we can perform operations to reduce its frequency to 1 and increase the count of distinct elements.
  4. If the frequency is already 1, we can skip that number.
  5. Return the count of distinct elements after performing the operations.

Time complexity: O(nlogn) where n is the number of elements in the array. Space complexity: O(n) for storing the frequencies of elements.

Solution Code

import java.util.*;

class Solution {
    public int maxOperations(int[] nums, int k) {
        Map<Integer, Integer> freq = new HashMap<>();
        for (int num : nums) {
            freq.put(num, freq.getOrDefault(num, 0) + 1);
        }
        
        List<Integer> values = new ArrayList<>(freq.values());
        Collections.sort(values, Collections.reverseOrder());
        
        int count = 0;
        for (int val : values) {
            if (val > 1) {
                int ops = Math.min(val - 1, freq.getOrDefault(k - val, 0));
                count += ops;
                freq.put(k - val, freq.getOrDefault(k - val, 0) - ops);
            }
        }
        
        return nums.length - count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3397 (Maximum Number of Distinct Elements After Operations)?

This page provides optimized solutions for LeetCode problem 3397 (Maximum Number of Distinct Elements After Operations) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 3397 (Maximum Number of Distinct Elements After Operations)?

The time complexity for LeetCode 3397 (Maximum Number of Distinct Elements After Operations) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3397 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3397 in Java, C++, or Python.

Back to LeetCode Solutions