Equilibrium index is an index when the sum of elements at lower indexes is equal to the sum of elements at higher indexes. Write a program to find Equilibrium index of an array.
For example:
Input:
[-14, 2, 10, 4 -8, 6, 0]
Output:
5
Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Equilibrium
{
class Program
{
static void Main()
{
int[] arr = { -14, 2, 10, 4 - 8, 6, 0 };
var result = EquilibriumIndex(arr);
if (result.Length > 0)
{
Console.WriteLine("Equilibrium Index");
foreach (var i in EquilibriumIndex(arr))
{
Console.WriteLine(i);
}
}
else
{
Console.WriteLine("Equilibrium Index Not Found");
}
Console.ReadKey();
}
public static int[] EquilibriumIndex(int[] arr)
{
var tempArr = new int[arr.Length];
for (var i = 1; i < arr.Length; i++)
{
tempArr[i] = tempArr[i - 1] + arr[i - 1];
}
var right = 0;
var result = new List<int>();
for (var i = arr.Length - 1; i >= 0; i--)
{
if (tempArr[i] == right)
{
result.Add(i);
}
right += arr[i];
}
return result.ToArray();
}
}
}