I'm trying to write an algorithm that will return True/False
whether a contiguous sequence in a sorted array that contains only positive integers, can sum up to N
.
For example:
Array = { 1, 2, 3, 4 };
6 is good! 1 + 2 + 3 = 6
8 is not good! 1 + 3 + 4 = 8, but it's not contiguous, since we skipped the 2.
This is what I have tried to do:
int[] arr = ...;
int headIndex = 1, tailIndex = 0, sum = arr[0];
while (sum != n)
{
if (sum < n)
{
sum += arr[headIndex++];
}
if (sum > n)
{
sum -= arr[tailIndex++];
}
}
return sum == n;
Obviously the above does not work (In some cases it might get stuck in an infinite loop). Any suggestions?
One thing I haven't mentioned earlier, and is very important- the algorithm's complexity must be low as possible.