Last active
October 13, 2022 03:06
-
-
Save fakemonk1/cc412195b3a3f6f7e44f61709bd9586e to your computer and use it in GitHub Desktop.
Codility Demo Test - Java Solution
This file contains hidden or 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
// 100% marks solution for the github demo test | |
// Find an index in an array such that its prefix sum equals its suffix sum. | |
class Solution { | |
public int solution(int[] A) { | |
if(A.length == 0){ | |
return -1; | |
} | |
long leftSum = 0; | |
long rightSum = getSum(A); | |
for (int i = 0; i < A.length ; i++) { | |
if(leftSum == rightSum - A[i]){ | |
return i; | |
} | |
leftSum = leftSum + A[i]; | |
rightSum = rightSum - A[i]; | |
} | |
return -1; | |
} | |
public long getSum(int[] A){ | |
long sum = 0; | |
for (int i :A){ | |
sum = sum + i; | |
} | |
return sum; | |
} | |
public static void main(String[] args) { | |
System.out.println(new Solution().solution(new int[]{-1, 3, -4, 5, 1, -6, 2, 1})); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment