You don't need to add up the array before processing. (per vnp responsevnp's comment)
Process the numbers from both ends, with the sum determining which end to take next.
Special conditions:
Less than 3 elements? => fail?
Is a single number success or fail?
What if only two numbers? where one is zero? both zero?
- Less than 3 elements? => fail?
- Is a single number success or fail?
- What if only two numbers? where one is zero? both zero?
algorithmAlgorithm:
initialize left index to -1 and right index to size of array, sum to zero.
loop:
if the left and right index are separated by 2 (with one index in the middle),
if the sum is 0, the middle index is the result, if not 0, then no solution.
If the sum is zero or positive, subtract the next element on the left.
else (is negative), add the next element from the right.
Is zero is a valid element? If so, then there could be multiple solutions. e.g. array 1 2 0 0 0 1 2 , index 2, 3, 4 are all solutions.
This method also avoids exceeding the max value for sum. If the array size is arbitrary, then there can always be a situation where adding all the elements can exceed the data type of sum. For this method, sum data type needs to be able to hold twice one array element.