Print maximum repeated value

Viewed 1041

I want to print the most repeated value in an array. If two values get repeated for maximum number of times, then print the largest one.I don't know how to print the largest one.I tried this.It just prints the print the most repeated value in an array.

int[] a= { 3,2,3,2,2};
        int count = 1, tempCount;
  int repeated = a[0];
  int temp = 0;
  for (int i = 0; i < (a.length - 1); i++)
  {
    temp = a[i];
    tempCount = 0;
    for (int j = 1; j < a.length; j++)
    {
      if (temp == a[j])
        tempCount++;
    }
    if (tempCount > count)
    {
     repeated = temp;
      count = tempCount;
    }
  }
  System.out.println(repeated);

If suppose the array elements are "3,2,3,3,2,4,5,4,6,4" then it has to print 4.(no. 3 three times and no. 4 three times.....But 4 is the greatest no. so the output is 4). Now how can i change my code?

5 Answers

Here:

repeated = temp;

You found a "new" repeated value, and you assign that unconditionally.

You need to distinguish two cases:

if (tempCount == count && temp > repeated)
{
   // updates for EQUAL count, but only for larger numbers
   repeated = temp;
   count = tempCount;
}
if (tempCount > count)
{
  // updates for larger count, small/large value doesn't matter
  repeated = temp;
  count = tempCount;
}

solves your problem!

change the j in this code to equal 0

for (int j = 1; j < a.length; j++)

as it skips the first element of the array which causes 3 to only be counted twice. also this logic should help if a number that is bigger has equal count

    int[] a= {3,2,3,2,2, 2, 4, 4, 5 ,5};
        int count = 1, tempCount;
        int repeated = a[0];
       int temp = 0;
       for (int i = 0; i < (a.length - 1); i++)
        {
       temp = a[i];
       tempCount = 0;
      for (int j = 0; j < a.length; j++)
    {
      if (temp == a[j])
        tempCount++;
    }
    if (tempCount ==count )
    {
        if(temp>repeated ){

     repeated = temp;
      count = tempCount;
        }
    }
    if (tempCount > count)
    {
     repeated = temp;
      count = tempCount;
    }
  }
    System.out.println(repeated);
    }
}

Edit i know its lazy but i kept it in the posters code format.

Instead of iterating over the array multiple times I'd probably just iterate once and count the occurences.

A Map<Integer, Integer> would help here, especially if the numbers can get negative or have "holes" (i.e. you have something like [1,2,5,9,1,9,9]). Here the key would be the number and the value would be the count. Example:

Map<Integer,Integer> counts = new HashMap<>();
for(int n : a ) {
  counts.merge(n, 1, (value,increment) -> value + increment );
}

In a next step you could either sort the entries by count and just take the highest or iterate again and track entries if their count is higher than the current maximum and their key is higher than the current key.

This is an approach that was called overkill in a comment below your question as someone else (but me) suggested to use a map. I think it is a valid approach, because of the use of the datastructure Map. See the comments in the code:

public static void main(String[] args) {
    int[] a = { 3, 2, 3, 2, 2 };
    int[] b = { 3, 2, 3, 3, 2, 4, 5, 4, 6, 4 };
    // create a data structure that holds the element and its count
    Map<Integer, Integer> occurrences = new HashMap<Integer, Integer>();
    /*
     * go through the array and store each element found as the key and how often it
     * was found as the value
     */
    for (int n : b) {
        if (occurrences.containsKey(n)) {
            /*
             * if the key is already contained, increment the value (additional occurrence
             * found)
             */
            occurrences.put(n, occurrences.get(n) + 1);
        } else {
            // otherwiese just add the key with value one (first occurrence)
            occurrences.put(n, 1);
        }
    }

    // now you have all the elements with its occurrences, go find the one to be displayed

    // print them once (not necessary for the result)
    occurrences.forEach((key, value) -> System.out.println(key + " : " + value));

    // get the largest number with the largest occurrence count
    int maxValue = 0;
    int maxKey = 0;

    for (int i : occurrences.keySet()) {
        if (occurrences.get(i) > maxValue) {
            // if you find a larger value, set the current key as max key
            maxKey = i;
            maxValue = occurrences.get(i);
        } else if (occurrences.get(i) == maxValue) {
            /*
             * if you find a value equal to the current largest one, compare the keys and
             * set/leave the larger one as max key
             */
            if (i > maxKey) {
                maxKey = i;
            }
        } else {
            // no need for handling a smaller key found
            continue;
        }
    }

    System.out.println("Largest key with largest value is " + maxKey);
}

Here is the solution to your problem. Read the comments in the code for more understanding. Your code has a complexity of O(n^2). Below code has O(n) complexity and is much faster.

 public static void main(String[] args){
    int[] arr = new int[]{3,2,3,3,2,4,5,4,6,4};
    // Assuming A[i] <= 100. Using freq[] to capture the frequency of number
    // freq[] will behave as a Map where index will be the number and freq[index] will be the frequency
    // of that number
    int[] freq = new int[101];

    for(int i=0;i<arr.length;i++){
        int num = arr[i];
        freq[num]++;
    }
    int max = 0;
    int ans = 0;
    for(int i=0;i<freq.length;i++){
        if(freq[i] >= max){
            ans = i;
            max = freq[i];
        }
    }
    System.out.println(ans);
}
Related