Created
May 14, 2018 14:26
-
-
Save okplanbo/0f8b0928fe464f3b7fee42c6af230ae4 to your computer and use it in GitHub Desktop.
Finding an equilibrium index in an int array
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
public int getEquilibrium(int[] array) { | |
long totalSum = sum(array); | |
long lowSum = 0L; | |
for (int i = 0; i < array.length; i++) { | |
totalSum -= array[i]; | |
if (lowSum == totalSum) { | |
return i; | |
} | |
lowSum += array[i]; | |
} | |
return -1; | |
} | |
public long sum(int[] array) { | |
return Arrays.stream(array).asLongStream().sum(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment