Given an array A of n positive numbers. The task is to find the first Equilibium Point in the array.
Equilibrium Point in an array is a position such that the sum of elements before it is equal to the sum of elements after it.
// { Driver Code Starts
#include <iostream>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
// Function to find equilibrium point in the array.
// a: input array
// n: size of array
int equilibriumPoint(long long a[], int n)
{
int start = a[0], end = a[n - 1];
int j = n - 2, index = -1;
int i = 1;
// cout << a[n - 1] << a[n - 2];
while (j > i)
{
if (start < end)
{
start = start + a[i];
// cout << start << " ";
i++;
// cout << i << " ";
// if ((start == end) && ((j - i) == 2))
// {
// index = i;
// }
}
if (start > end)
{
end = end + a[j];
// cout << end << " ";
// cout << j << " ";
j--;
// if ((start == end) && ((j - i) == 2))
// {
// index = i;
// cout << i << " ";
// }
}
if (start == end)
{
// cout << i;
if (((j - i) <= 0) && (j >= i))
{
index = i + 1;
// cout << i << " ";
}
start = start + a[i];
i++;
}
}
// cout << " ";
// cout << index;
if (n == 1)
{
index = 1;
}
return index;
}
};
// { Driver Code Starts.
int main()
{
long long t;
// taking testcases
cin >> t;
while (t--)
{
long long n;
// taking input n
cin >> n;
long long a[n];
// adding elements to the array
for (long long i = 0; i < n; i++)
{
cin >> a[i];
}
Solution ob;
// calling equilibriumPoint() function
cout << ob.equilibriumPoint(a, n) << endl;
}
return 0;
}
// } Driver Code Ends
Happy Coding 😊.