Skip to content

Instantly share code, notes, and snippets.

@milosmns
Created February 18, 2017 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milosmns/cdf9dc210aa09e98daa43a59d7e4968a to your computer and use it in GitHub Desktop.
Save milosmns/cdf9dc210aa09e98daa43a59d7e4968a to your computer and use it in GitHub Desktop.
Solution to the array equilibrium problem on Codility
class Solution {
public int solution(int[] A) {
// false inputs
if (A == null || A.length == 0) {
return -1;
}
// 1-length array
if (A.length == 1) {
return 0;
}
// 2-length array
if (A.length == 2) {
if (A[0] == 0) {
return 1;
} else if (A[1] == 0) {
return 0;
} else {
return -1;
}
}
// normal case
long rightSide = 0;
for (int i = 0; i < A.length; i++) {
rightSide += A[i];
}
long leftSide = 0;
for (int i = 0; i < A.length; i++) {
if (leftSide == rightSide - A[i]) {
return i;
}
leftSide += A[i];
rightSide -= A[i];
}
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment