title: Codility - Counting Elements Lessons : fastest algorithm swap
body: <p>i am <a href="https://codility.com/media/train/2-CountingElements.pdf" rel="nofollow">studying Codility chapter 2 : Counting elements</a>.</p>
  
  <p>I tried to make the exercise, and i think I have a good solution O(n). is It a valid solution ?
  Is it a better solution that the BEST solution proposed in te lesson ?</p>
  
  <p><strong>Problem:</strong> You are given an integer m (1  m  1 000 000) and two non-empty, zero-indexed arrays A and B of n integers, a0,a1,...,an−1 and b0,b1,...,bn−1 respectively (0  ai,bi  m). The goal is to check whether there is a swap operation which can be performed on these arrays in such a way that the sum of elements in array A equals the sum of elements in array B after the swap. By swap operation we mean picking one element from array A and
  one element from array B and exchanging them.</p>
  
  <p><strong>I tested my solution with these values :</strong>
       int a[] = {2, 7, 12, 16};
       int b[] = {4, 8, 9};
       m = 16;</p>
  
  <p><strong>note:</strong> I commented the return to see the swapped values.</p>
  
  <pre><code> public int resultat(int[] A, int B[], int max) {
  
      int sumA = Arrays.stream(A).sum();
      int sumB = Arrays.stream(B).sum();
  
      int[] countA = count(A, max);
      int[] countB = count(B, max);
      int diff = sumA - sumB;
      int diffMin = 0;
  
      if (diff % 2 != 0) {
          return -1;
      }
      diffMin = diff / 2;
      if (sumA &gt; sumB) {
  
          if (diff &lt; countA.length &amp;&amp; diffMin &lt; countB.length &amp;&amp; countA[diff] != 0 &amp;&amp; countB[diffMin] != 0) {
              System.out.println("A:" + diff + "- B:" + diffMin);
              //return 1;
          }
      } else {
  
          if (diffMin &lt; countA.length &amp;&amp; diff &lt; countB.length &amp;&amp; countB[diff] != 0 &amp;&amp; countA[diffMin] != 0) {
              System.out.println("A:" + diffMin + "- B:" + diff);
              //return 1;
          }
      }
      return -1;
  
  }
  
  public int[] count(int[] X, int max) {
      int[] p = new int[max + 1];
      Arrays.fill(p, 0);
      for (int i = 0; i &lt; X.length; i++) {
          p[X[i]] += 1;
      }
      return p;
  }
  </code></pre>