I am using C++ to code the following logic:
An Array is given we have to traverse the array such that sum of array elements to its left must be equal to sum of elements to its right.
BTW this is hackerrank Problem.
Here's the code , but this is giving me time-out, that is my code is too slow for very large input, I want to make it faster.
int sumArray(int arr[],int start,int end){
int sum = 0;
for(int i=start;i<=end;i++)
sum += arr[i];
return sum;
}
// this is inside main
int ar[N];
for(int n=0;n<N;n++)
cin>>ar[n];
bool found = false;
if(N == 1)
found = true;
for(int i=1;i<N;i++){
int left = sumArray(ar,0,i-1);
int right = sumArray(ar,i+1,N-1);
if( left == right)
found = true;
}
if (found)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
This is how the problem works, this is given array 1 2 3
1 2 3 3
In the first test case, no such index exists.
In the second test case, A[0] + A[1] = A[3]. So 2(start from 0) is the position where this condition occurs.
this is slow for N=10000 elements in array it excceds 2ms time limit
So where should my code be improved? My mind says I should give a try with dynamic programming because I am calling same process each time and start it from zero. Is there any good method to do this. Or is there a better way to make above code work for large inputs (I know there's some better way)?
All suggestions are warmly welcomed!!
ar[0]+ar[1]
? how many times should it be? Edit: having the full code (what is N?), and some context (I guess it is tested with a software, and that numbers aren't manually entered). \$\endgroup\$