Created
June 22, 2016 01:59
-
-
Save tiagopereira17/2943fc186a98192442fadb71b0e8f3ad to your computer and use it in GitHub Desktop.
Minimize the value |(A[0] + ... + A[P-1]) - (A[P] + ... + A[N-1])|.
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 class TapeEquilibrium { | |
public int solution(int[] A) { | |
int start = A[0]; | |
int end = sum(A) - start; | |
int minDif = Math.abs(start - end); | |
for(int i = 1; i < A.length - 1; i++) { | |
start += A[i]; | |
end -= A[i]; | |
int dif = Math.abs(start - end); | |
if(dif < minDif) { | |
minDif = dif; | |
} | |
} | |
return minDif; | |
} | |
public int sum(int[] array) { | |
if(array == null || array.length == 0) { | |
return 0; | |
} | |
int sum = 0; | |
for(int i = 0; i < array.length; i++) { | |
sum += array[i]; | |
} | |
return sum; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment