Skip to content

Instantly share code, notes, and snippets.

@l1x
Created March 20, 2017 09:47
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save l1x/b2ba507036c41b98343912a94c51800b to your computer and use it in GitHub Desktop.
Equilibrium Index
// A zero-indexed array A consisting of N integers is given. An equilibrium index of this array is any integer P such that 0 ≤ P < N and the sum of elements of lower indices is equal to the sum of elements of higher indices, i.e.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class Solution {
public int solution(int[] A) {
List<Integer> list = Arrays.stream(A).boxed().collect(Collectors.toList());
final long sum = IntStream.of(A).sum();
long leftSum = 0;
long rightSum = 0;
for (int i = 0; i < A.length; i++) {
rightSum = sum - (leftSum + A[i]);
if (leftSum == rightSum) {
return i;
}
leftSum += A[i];
}
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment