Mr. Jack is now judging arrays! He
wants to see if an array can be split. He wants to split it only if the sum of the array on one side is equal to sum
the array on the other side.
For example, in the array: 1 1 1 2 1, it can be split such that 1 1 1 are on one side and 2 1 are on the other side. However the array 2 1
can't be split
Write a method Met that accepts as parameter an integer array and prints true if the array can be split, otherwise it prints false.
Note: the array will be of length greater than 1.
The Met method has to be inside a Solution class. Please check the code editor for the ideal method definition
Example Input: 11121
Output: true
Example Input: 21121
Output: false
Example Input: 10 10
Output: true
Example Input: 431114
Output: true
Answers
Program in C++:
#include<iostream>
using namespace std;
class solution
{
public:
bool Met(int A[], int n)
{
int left = 0;
for(int i = 0; i < n; i++)
{
left = left + A[i];
int right = 0;
for(int j = i+1; j < n; j++)
{
right = right + A[j];
}
if(left == right)
{
return true;
}
}
return false;
}
};
int main()
{
int n;
cout<<"Enter number of elements in the array : ";
cin>>n;
if(n < 1)
{
cout<<"Invalid input";
return 0;
}
int A[n];
cout<<"Enter elements in the array : ";
for(int i = 0; i < n; i++)
{
cin>>A[i];
}
solution s;
cout<<boolalpha<<s.Met(A, n);
return 0;
}
Output 1:
Enter number of elements in the array : 5
Enter elements in the array : 1 1 1 2 1
true
Output 2:
Enter number of elements in the array : 5
Enter elements in the array : 2 1 1 2 1
false
Output 3:
Enter number of elements in the array : 2
Enter elements in the array : 10 10
true
Output 4:
Enter number of elements in the array : 6
Enter elements in the array : 4 3 1 1 1 4
true