Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to get the minimum elements to be deleted to make an array with same values in Java

1 Answer

0 votes
import java.util.HashMap;

public class MyClass {
    public static int minElementsToBeDelete(int arr[]) {
        HashMap<Integer,Integer> frequency = new HashMap<Integer,Integer>();
        int size = arr.length;
        
        for (int i = 0; i < size; i++) {
            if (frequency.containsKey(arr[i]))
                frequency.put(arr[i], frequency.get(arr[i]) + 1);
            else
                frequency.put(arr[i], 1);
        }
        
        int max_frequency = Integer.MIN_VALUE;
        for (int i:frequency.keySet())
            max_frequency = Math.max(max_frequency, frequency.get(i));
            
        return size - max_frequency;
    }
    
    public static void main(String args[]) {
        int arr[] = { 3, 5, 3, 8, 3, 3, 9, 3, 2, 2 };

        System.out.println(minElementsToBeDelete(arr));
    }
}



/*
run:

5

*/

 



answered Dec 12, 2022 by avibootz
...