I received a codility test the other day for a job, as such I've been practicing using some of the problems from their training page Link
Unfortunately, I've only been able to get 83/100 on the Tape-Equilibrium question:
A non-empty zero-indexed array A consisting of N integers is given. Array A represents numbers on a tape.
Any integer P, such that0 < P < N
, splits this tape into two non−empty parts:A\[0], A\[1], …, A\[P − 1] and A\[P], A\[P + 1], …, A\[N − 1]
.
The difference between the two parts is the value of:|(A\[0] + A\[1] + … + A\[P − 1]) − (A\[P] + A\[P + 1] + … + A\[N − 1])|
In other words, it is the absolute difference between the sum of the first part and the sum of the second part.
Write a function that, given a non-empty zero-indexed array A of N integers, returns the minimal difference that can be achieved.
Example:
A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 4 A[4] = 3
We can split this tape in four places:
P = 1
, difference = |3 − 10| = 7
P = 2
, difference = |4 − 9| = 5
P = 3
, difference = |6 − 7| = 1
P = 4
, difference = |10 − 3| = 7
In this case I would return 1 as it is the smallest difference.
N is an int, range [2..100,000]; each element of A is an int, range [−1,000..1,000]. It needs to be O(n) time complexity,
My code is as follows:
import java.math.*;
class Solution {
public int solution(int[] A) {
long sumright = 0;
long sumleft = 0;
long ans;
for (int i =1;i<A.length;i++)
sumright += A[i];
sumleft = A[0];
ans =Math.abs(Math.abs(sumright)+Math.abs(sumleft));
for (int P=1; P<A.length; P++)
{
if (Math.abs(Math.abs(sumleft) - Math.abs(sumright))<ans)
ans = Math.abs(Math.abs(sumleft) - Math.abs(sumright));
sumleft += A[P];
sumright -=A[P];
}
return (int) ans;
}
I went a bit mad with the Math.abs. The two test areas it fails on are "double" (which I think is two values, -1000 and 1000, and "small". http://codility.com/demo/results/demo9DAQ4T-2HS/
Any help would be appreciated, I want to make sure I'm not making any basic mistakes.
Your solution is already O(N). You need to remove the abs from sumleft and sumright.
if (Math.abs( sumleft - sumright ) < ans)
{
ans = Math.abs( sumleft - sumright );
}
Also before the second for loop,
ans =Math.abs( sumleft - sumright );
It should work.