Write a function to find if there exists at least one point / index , whose left side sum of elements equals right side sum of elements.
For example:
If the given array is 12346, position '4'(1-based indexing) satisfies the condition. i.e.,1+2+3 = 6
If the given array is 5237, position '3' satisfies the condition. 5+2 = 7
#include <stdio.h>
/* Size of the array */
#define MAX 1000000
int main(void)
{
int T,A[MAX],i,sum,left,flag,N;
/* Get the number of test cases */
scanf("%d",&T);
while(T--)
{
sum=0;
left=0;
flag=0;
/* Get the number of elements of the array */
scanf("%d",&N);
for(i=0;i<N;i++)
{
/* Get the elements of the array */
scanf("%d",&A[i]);
/* Calculate the sum of the elements of the array thereby */
sum=sum+A[i];
}
for(i=0;i<N;i++)
{
/* If ith element is subtracted from the sum, then sum has total sum of the right side */
sum=sum-A[i];
/* left has the initial value 0 */
if(left==sum)
{
flag=1;
break;
}
/* It adds up every element from the start as we move through the entire array */
left=left+A[i];
}
/* If such an index exists in the given array */
if(flag==1)
printf("YES\n");
/* If such an index doesn't exists in the given array */
else
printf("NO\n");
}
return 0;
}
C++ Implementation:
#include <iostream>
#define MAX 1000000
using namespace std;
int main()
{
int T,A[MAX],i,sum,left,flag,N;
/* Get the number of test cases */
cin>>T;
while(T--)
{
sum=0;
left=0;
flag=0;
/* Get the number of elements of the array */
cin>>N;
for(i=0;i<N;i++)
{
/* Get the elements of the array */
cin>>A[i];
/* Calculate the sum of the elements while getting the input */
sum=sum+A[i];
}
for(i=0;i<N;i++)
{
/* Calculate the right sum */
sum=sum-A[i];
/* Check whether the left sum equals the right sum */
if(left==sum)
{
flag=1;
break;
}
/* Keep track of the left sum */
left=left+A[i];
}
/* Print YES if such an index exists in the array */
if(flag==1)
cout<<"YES\n";
/* Print NO if such an index doesn't exists in the array */
else
cout<<"NO\n";
}
return 0;
}
Java Implementation:
import java.util.Scanner;
class TestClass {
public static void main(String args[] ) throws Exception
{
/* Create a scanner object to accept input from the user */
Scanner in=new Scanner(System.in);
/* Get the number of test cases from the user */
int T=in.nextInt();
while((T--)>0)
{
/* Get the number of elements of array from the user */
int N=in.nextInt();
int sum=0;
int left=0;
int flag=0,i;
int arr[]=new int[N];
for(i=0;i<N;i++)
{
/* Get the elements of the array */
arr[i]=in.nextInt();
/* Calculate the sum of the elements of the array */
sum+=arr[i];
}
for(i=0;i<N;i++)
{
/* Find the right sum */
sum=sum-arr[i];
/* Compare with left sum */
if(sum==left)
{
flag=1;
break;
}
/* Update left sum for every index move */
left=left+arr[i];
}
/* If there exists such an index, print YES */
if(flag==1)
System.out.println("YES");
/* Else print NO*/
else
System.out.println("NO");
}
}
}