Posted By

ariellephan on 10/27/10


Tagged


Versions (?)

Equilibrium index


 / Published in: Java
 

Given an array A of N integers, equi(A) is any index i for which: (1) i is a valid index into A, i.e. 0 <= i < N (2) The sum of integers preceding (but not including) i is equal to the sum of integers following (again not including) i. i.e.: A[0]+A[1]+...+A[i-1] = A[i+1]+A[i+2]..+A[N-1]

If there is no such index i, equi(A) = -1.

  1. int equi(int[] A) {
  2. int i;
  3. int s = 0;
  4. for (i = 0; i < A.length; ++ i) s += A[i];
  5. while (i-- > 0 && A[i] != s) s -= 2 * A[i];
  6. return i;
  7. }

Report this snippet  

You need to login to post a comment.