Equilibrium index of a sequence is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes

#include <stdio.h>

int equilibrium(int a[], int n)
{
int sum = 0;

int i;

/*Find sum of the array*/

for(i = 0; i < n; ++i)
sum += a[i];


/*find leftsum of an index i
      rightsum = sum - leftsum - a[i];
    */
int leftsum = 0;

for(i = 0; i < n; ++i)
{
sum -= a[i];

if(leftsum == sum)
return i;

leftsum += a[i];
}


return -1;
}


int main()
{
int a[] = {-7, 1, 5, 2, -4, 3, 0};

printf("%d\n", equilibrium(a, 7));
}
Advertisements

One thought on “Equilibrium index of a sequence is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s