title: The most common element in 2d array.How to optimize?
body: <p>I have this task, find the most commonly seen element in int[][] array and print the number and times repeated.I solved the problem.</p>
  
  <p>A friend of mine said that having 4 <code>for()</code>s is a bad idea.So I decided to try optimising it to remove one or two, but couldn't figure a way.</p>
  
  <p>So here it is:</p>
  
  <pre><code>     int cnt, element = arr[0][0], numberRepeats = 0;//cnt-counter,what's the element ,how many times it's repeated
       for (int i = 0; i &lt; arr.length; i++) {
          for (int j = 0; j &lt; arr[i].length; j++) {//those two for's are for the current element
              cnt = 0;//counter is nullified
              for (int j2 = i; j2 &lt; arr.length; j2++) {
                  for (int k = 0; k &lt; arr[j2].length; k++) {//and those two are the compared element
                      if (arr[i][j] == arr[j2][k]) {//if the current element is the same as the compared element,increase counter
                          cnt++;
                      }
                  }
  
              if (cnt &gt; numberRepeats) {//after the compared element is done comparing and the number of repeats of the current element is more then the lastly checked element
                  element = arr[i][j];//we get the element ,and how many times it's repeated
                  numberRepeats = cnt;
              }
          }
      }
  }
  </code></pre>
  
  <p>The only optimisation that I could think of was starting the counting from the current element till the end.</p>
  
  <p>Please give me some more ideas. All the answers I could find were for the 1D array, and they were all pretty much the same code.</p>