-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEquilibriumIndex.cs
More file actions
43 lines (37 loc) · 1.15 KB
/
EquilibriumIndex.cs
File metadata and controls
43 lines (37 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using System;
using System.Collections.Generic;
namespace DA.Algorithms.Problems
{
public static class EquilibriumIndex
{
/// <summary>
/// Find balance point index.
/// An index is balanced if the elements in the left of it
/// and elements in the right of it have same sum.
/// </summary>
///
/// <exception cref="System.ArgumentNullException" />
///
/// <param name="array"></param>
public static int FindBalancedPoint (int[] array)
{
if (array == null)
throw new System.ArgumentNullException ();
if (array.Length == 1)
return 0;
int first = 0;
int second = 0;
for (int i = 0; i < array.Length; i++)
second += array[i];
for (int index = 0; index < array.Length; index++)
{
if (first == second)
return index;
if (index < array.Length - 1)
first += array[index];
second -= array[index + 1];
}
return -1;
}
}
}