Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Monday, February 22, 2021

Maximum Number with least frequency


 Problem : 

The elements of the array consists of positive integers. You have to find the largest element with minimum frequency.

 

Code  : 

 public static int LargButMinFreq(int arr[], int n)
    {
        Map<Integer, Integer> map = new HashMap<>();
        for(int i : arr) {
            map.put(i, map.getOrDefault(i, 0)+1);
        }
        int maxNumber = Integer.MIN_VALUE;
        int minFrequency = Integer.MAX_VALUE;
        for(int i: arr) {
            if(map.get(i) <= minFrequency && i>maxNumber) {
                minFrequency = map.get(i);
                maxNumber = i;
            }
        }
        return maxNumber;
    }

0 Comments:

Post a Comment

Stats