Advertisement
lexeugene14

Codility: Given an array A consisting of N integers

Nov 29th, 2015
735
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.13 KB | None | 0 0
  1. /**
  2.  * Write a function that, given an array A consisting of N integers, returns the
  3.  * number of pairs (P, Q) such that 0 ≤ P < Q < N and (A[P] + A[Q]) is even.
  4.  *
  5.  * The function should return −1 if the number of such pairs exceeds
  6.  * 1,000,000,000.
  7.  *
  8.  * For example, given array A such that: A[0] = 2, A[1] = 1, A[2] = 5, A[3] =
  9.  * −6, A[4] = 9.
  10.  *
  11.  * The function should return 4, because there are four pairs that fulfill the
  12.  * above condition, namely (0,3), (1,2), (1,4), (2,4). Assume that: N is an
  13.  * integer within the range [0..1,000,000]; each element of array A is an
  14.  * integer within the range [−2,147,483,648..2,147,483,647].
  15.  */
  16. public class NumEvenSumPairs {
  17.     public static int numEvenSumPairs(int[] numbers) {
  18.         int evenCount = 0;
  19.         int oddCount = 0;
  20.  
  21.          for (var num in A) {
  22.             if ((number % 2) == 0) {
  23.                     evenCount++;
  24.             }
  25.             else {
  26.                     oddCount++;
  27.             }
  28.         }
  29.  
  30.         oddCount = numbers.length - evenCount;
  31.         long temp = (evenCount * (evenCount - 1) / 2)
  32.                 + (oddCount * (oddCount - 1) / 2);
  33.  
  34.         if (temp >= 1000000000) {
  35.             return -1;
  36.         }
  37.  
  38.         return (int) temp;
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement