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
...