Created
February 18, 2017 16:10
-
-
Save milosmns/cdf9dc210aa09e98daa43a59d7e4968a to your computer and use it in GitHub Desktop.
Solution to the array equilibrium problem on Codility
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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