Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 570f39e

Browse files
author
Ram swaroop
committed
equilibrium index : done
1 parent b04d944 commit 570f39e

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package me.ramswaroop.arrays;
2+
3+
/**
4+
* Created by IntelliJ IDEA.
5+
*
6+
* @author: ramswaroop
7+
* @date: 8/22/15
8+
* @time: 11:56 AM
9+
*/
10+
public class EquilibriumIndex {
11+
12+
/**
13+
* EQUILIBRIUM INDEX of an array is an index such that the sum of elements at lower
14+
* indexes is equal to the sum of elements at higher indexes.
15+
* <p/>
16+
* For example, in an array A = {-7, 1, 5, 2, -4, 3, 0}
17+
* <p/>
18+
* 3 is an equilibrium index, because
19+
* A[0] + A[1] + A[2] = A[4] + A[5] + A[6]
20+
* <p/>
21+
* 6 is also an equilibrium index, because sum of zero elements is zero,
22+
* i.e., A[0] + A[1] + A[2] + A[3] + A[4] + A[5] = 0
23+
* <p/>
24+
* 7 is not an equilibrium index, because it is not a valid index of array A.
25+
*
26+
* @param a
27+
* @return equilibrium index of array {@param a}.
28+
*/
29+
public static int getEquilibriumIndex(int[] a) {
30+
int totalSum = 0, leftSum = 0;
31+
32+
for (int i = 0; i < a.length; i++) {
33+
totalSum += a[i];
34+
}
35+
36+
for (int i = 0; i < a.length; i++) {
37+
totalSum -= a[i]; // totalSum now holds the right sum
38+
if (leftSum == totalSum) {
39+
return i; // left sum == right sum
40+
}
41+
leftSum += a[i]; // update left sum
42+
}
43+
44+
return -1;
45+
}
46+
47+
public static void main(String a[]) {
48+
System.out.println(getEquilibriumIndex(new int[]{-7, 1, 5, 2, -4, 3, 0}));
49+
System.out.println(getEquilibriumIndex(new int[]{-7, 1, 5, 0, 0, 0, 0, 1, 2, -4, 1, 3, 0}));
50+
System.out.println(getEquilibriumIndex(new int[]{4, 5, 2, 1, 6, 7, 8, 0, 1}));
51+
System.out.println(getEquilibriumIndex(new int[]{0}));
52+
System.out.println(getEquilibriumIndex(new int[]{0, 0, 0}));
53+
System.out.println(getEquilibriumIndex(new int[]{1, 1}));
54+
System.out.println(getEquilibriumIndex(new int[]{1, 1, 1}));
55+
}
56+
}

0 commit comments

Comments
 (0)