Skip to content

Instantly share code, notes, and snippets.

@le-doude
Created June 18, 2014 08:11
Show Gist options
  • Save le-doude/a083e13130e0933c0060 to your computer and use it in GitHub Desktop.
Save le-doude/a083e13130e0933c0060 to your computer and use it in GitHub Desktop.
Solution for the TapeEquilibrium test at https://codility.com/demo/take-sample-test/tape_equilibrium
/**
* Created by edouard on 14/06/18.
*/
class Solution {
public int solution(int[] A) {
int maxIndex = A.length - 1;
int[] leftSum = new int[A.length];
leftSum[0] = A[0];
for (int i = 1; i < A.length; i++) {
leftSum[i] = A[i] + leftSum[i - 1];
}
int[] rightSum = new int[A.length];
rightSum[maxIndex] = A[maxIndex];
for (int i = A.length - 2; i >= 0; i--) {
rightSum[i] = A[i] + rightSum[i + 1];
}
int minDiff = Integer.MAX_VALUE;
for (int i = 1; i < A.length; i++) {
minDiff = Math.min(minDiff, Math.max(rightSum[i], leftSum[i - 1]) - Math.min(rightSum[i], leftSum[i - 1]));
}
return minDiff;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment