Created
April 12, 2015 17:50
-
-
Save stephen-maina/c64266ab34c2337eba98 to your computer and use it in GitHub Desktop.
TapeEquilibrium Codility
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
import java.lang.Math; | |
import java.util.stream.IntStream; | |
class Solution { | |
public int solution(int[] A) { | |
// write your code in Java SE 8 | |
if(A.length==0) | |
{ | |
return 0; | |
} | |
if(A.length==1){ | |
return A[0]; | |
} | |
if(A.length==2){ | |
return Math.abs(A[0]-A[1]); | |
}int ans=0; | |
int sumLeft=IntStream.of(A).skip(1).sum(); | |
int sumRight=A[0]; | |
ans=Math.abs(sumLeft+sumRight); | |
for(int index=1;index<A.length-1;index++){ | |
int diff=Math.abs(sumLeft-sumRight); | |
if (diff<ans){ | |
ans = diff; | |
} | |
sumLeft -= A[index]; | |
sumRight +=A[index]; | |
} | |
return ans; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment