I'm trying to do a simple problem in C that goes like this:
Any integer
P
, such that0 < P < N
, splits this tape into two non-empty parts:A[0]
,A[1]
, ...,A[P − 1]
andA[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.Also:
N
is an integer within the range[2..100,000]
; each element of arrayA
is an integer within the range[−1,000..1,000]
.
I came up with the following code:
int solution(int A[], int N) {
// write your code in C99
double firstSum = A[0];
double secondSum = 0;
double curDiff, maxDiff, maxIndex = 1;
for(int i = 1; i < N; i++)
{
secondSum += A[i];
}
curDiff = abs(firstSum - secondSum);
maxDiff = curDiff;
for(int i = 2; i < N; i++)
{
secondSum -= A[i-1];
firstSum += A[i-1];
curDiff = abs(firstSum - secondSum);
if(curDiff > maxDiff)
maxIndex = i;
}
return maxIndex;
}
Which, according to the site I did this test on, is really bad. The site says the code failed most of the tests they ran, but I can't figure out why (they don't supply the tests). The code seems fine to me. Furthermore, they said that a solution is to be O(n) worst case space complexity (not including input) and I've managed to do it in O(1), so something seems off.