Given an array having positive integers, find a continous subarray which adds to a given number.
It can be done O(n).
My logic is as follows:- Keep adding elements to a running sum till it is either equal to given number or is greater than the given number. As soon as we add a number and the running number is greater than the given number we subtract the elements from the beginning of the array till it is again less than the given number. After the current sum is less than the given number we add the next element and check and continue the same process.
bool FindSum(int* A, int n, int sum, int& start, int& end)
{
int cursum = 0;
int start_index = 0, end_index = 0;
for (; end_index < n; )
{
if (cursum > sum)
{
cursum -= A[start_index];
start_index++;
}
if (cursum == sum)
{
start = start_index;
end = end_index;
return true;
}
if (cursum < sum)
{
cursum += A[end_index];
end_index++;
}
}
return false;
}
int main ( int argc, char *argv[] )
{
int A[] = {2, 1, 8, 2, 2, 4};
int start,end;
int sum = 12;
int size = sizeof(A) / sizeof(A[0]);
if (FindSum(A, size, sum, start, end))
{
cout << start << " " << end << endl;
}
else
printf("NO ANSWER.\n");
return 0;
}