Header Ads Widget

Equilibrium point in an array

 Problem:-

Given an array A of n positive numbers. The task is to find the first Equilibrium 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.

Input Format :-

1. first line of input contain a number n (length of the array).
2. second line n space separated numbers (element of the array).

Output Format:- 

if equilibrium exist then return the index of the equilibrium point (1 index based ). else return -1.

Example 1:

Input: 
n = 5 
A[] = {1,3,5,2,2} 
Output: 3 
Explanation:  
equilibrium point is at position 3 
as elements before it (1+3) = 
elements after it (2+2).

Example 2:

Input:
n = 1
A[] = {1}
Output: 1
Explanation:
Since its the only element hence
its the only equilibrium point.

C++ code:-


#include<bits/stdc++.h>
using namespace std;

int equilibriumPoint(long long a[], int n) {
if(n==1)
return 1;
long long sum=0;
for(int i=0;i<n;i++)
{
sum+=a[i];
}
long long b=0;
for(int i=0;i<n-1;i++)
{
b+=a[i];
if(b==(sum-b-a[i+1]))
return i+2;
}
return -1;
}

int main()
{
int n;
cin>>n;
long long a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
int ans=equilibriumPoint(a,n);
cout<<ans<<endl;
return 0;
}




Wipro :-

Infytq :-

Key Points;-

Hackerrank:-


C-tutorial:-

See more:-










Post a Comment

0 Comments