This java solution to the codility problem TapeEquillibrium scored 100%

Logic: First find the sum of all the integers in the array. Then start to iterate over from first partition point being the first position until the second last item and calculate the left sum and the right sum. Find the difference between them and compare it with the minimum difference so far calculated, if its less than that then set the minimum difference to this new lower value..continue.

With the end of the for loop the correct minimum difference is reached. Return that!

Also check out the Math functions..they are so convenient! abs and min!

    public int solution(int[] A) {
        long totalSum=0;
        int minDifference = Integer.MAX_VALUE;
        for (int i=0; i<A.length;i++) {
            totalSum = totalSum + A[i];
        long leftSum = 0;
        long rightSum = 0;
        for (int i=0; i<A.length - 1; i++) {
            leftSum = leftSum + A[i];
            rightSum = totalSum - leftSum;
            int currentDifference = (int) Math.abs(leftSum - rightSum);
            minDifference = Math.min(currentDifference, minDifference);
        return minDifference;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s