Good day! That's what happened with me. Displays the desired result, but after 2 cycles.

How to do with one?

public class Main { public static void main(String[] args) { int[] dArray = {20, 13, 20, 14, 20, 14}; int max = 0; int k = 0; for (int i = 0; i < dArray.length; i++) { if (max < dArray[i]) max = dArray[i]; } for (int i = 0; i < dArray.length; i++) { if (dArray[i] == max) k++; } System.out.println(k); } } 
  • Brilliant! I would never have figured out how to do this with two or more cycles. - Sergey

2 answers 2

You just need to reset k if a new maximum appears. And if the maximum coincides with the value of the array - then increase it k

An example is:

 int[] dArray = {21, 20, 13, 20, 14, 20, 14, 21}; int max = 0; int countMax = 0; for (int i = 0; i < dArray.length; i++) { if (max < dArray[i]) { max = dArray[i]; countMax = 0; } if (max == dArray[i]) countMax++; } System.out.println(countMax); 

http://ideone.com/dHCpw7

  • Thank you, it turned out so simple. - Maxim Yurchenko

For example, like this:

 public class Main {
   public static void main (String [] args) {
     int [] dArray = {20, 13, 20, 14, 20, 14};
     int maxValue = Integer.MIN_VALUE;  // Negative is it impossible? 
     int maxCount = 0;
     for (int i = 0; i <dArray.length; i ++) {
       if (dArray [i]> maxValue) { 
         maxValue = dArray [i];
         maxCount = 1;
       } else if (dArray [i] == maxValue) maxCount ++; 
     }
     System.out.printf ("Found% d occurrences of% d \ n", " 
                         maxCount, maxValue);
   }
 }