Wednesday, 20 December 2023

Highest / Lowest Frequency Elements

Coding Ninjas Problem Link


import java.util.HashMap;

import java.util.Map;

import java.util.Arrays;

import java.util.Scanner;

public class MyFirstClass {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int v[] = {11,13,3,14,17,3,7,9,1,11,9,15,5,2,2,3,11,2};

        int r[] = getFrequencies(v);

        for (int i : r) {

            System.out.print(i+" ");

        }

    }

    public static int[] getFrequencies(int []v) {

        // Write Your Code Here

        HashMap<Integer,Integer> mp = new HashMap<>();

        int n = v.length;

        //int result[] = new int[n];

        for(int i=0; i<v.length; i++)

        {

            int freq = 0;

            if(mp.containsKey(v[i])) 

            {

                freq = mp.get(v[i]);

            }

            freq += 1;

            mp.put(v[i],freq);

        }

        int maxele=0;int minele=0;

        int minfreq=n;

        int maxfreq = 0;

        for(HashMap.Entry<Integer,Integer> entry : mp.entrySet())

        {

            int element = entry.getKey();

            int count = entry.getValue();

            if(count>=maxfreq)

            {

                if(count==maxfreq) maxele = Math.min(maxele, element);

                else maxele = element;

                maxfreq = count;

            }

            if(count<=minfreq)

            {

                //minele = Math.min(element,minele);

                if(count==minfreq) minele = Math.min(minele, element);

                else minele = element;

                minfreq = count;

            }

        }

        int result[] = new int[2];

        result[0] = maxele;

        result[1] = minele;

        return result;

    }

}


No comments:

Post a Comment

Good thoughtful question on Binary search on answers

Problem link:  https://leetcode.com/problems/maximize-score-of-numbers-in-ranges/description/ Solution: //import java.util.Arrays; class So...