55public class EquilibriumIndex {
66 public static void main (String [] args ) {
77
8- findEquilibriumIndex ();
8+ ArrayList <Integer > arrayList = new ArrayList <>(100 );
9+
10+ arrayList .add (-7 );
11+ arrayList .add (1 );
12+ arrayList .add (5 );
13+ arrayList .add (2 );
14+ arrayList .add (-4 );
15+ arrayList .add (3 );
16+ arrayList .add (0 );
17+ // arrayList.add(-3);
18+ // arrayList.add(6);
19+ // arrayList.add(2);
20+ // arrayList.add(4);
21+ // arrayList.add(5);
22+ // arrayList.add(-1);
23+ // arrayList.add(2);
24+ // arrayList.add(-3);
25+ // arrayList.add(6);
26+ // arrayList.add(2);
27+ // arrayList.add(4);
28+ // arrayList.add(5);
29+ // arrayList.add(-1);
30+ // arrayList.add(2);
31+
32+ int index = findEquilibriumIndex (arrayList );
33+
34+ System .out .println ("Equilibrium Index is " + index );
935 }
1036
1137 static int getPrefixSumOfAnIndex (int index , ArrayList <Integer > arrayList ){
@@ -21,19 +47,41 @@ static int getPrefixSumOfAnIndex(int index, ArrayList<Integer> arrayList){
2147 return prefixSum ;
2248 }
2349
24- static void findEquilibriumIndex () {
50+ static int findEquilibriumIndex (ArrayList < Integer > arrayList ) {
2551
26- ArrayList <Integer > arrayList = new ArrayList <>( 10 );
52+ ArrayList <Integer > prefixArray = getPrefixSumArrayOfAnArray ( arrayList );
2753
28- arrayList .add (-3 );
29- arrayList .add (6 );
30- arrayList .add (2 );
31- arrayList .add (4 );
32- arrayList .add (5 );
33- arrayList .add (-1 );
34- arrayList .add (2 );
54+ System .out .println (prefixArray );
55+
56+ int length = prefixArray .size ()-1 ;
57+
58+ for (int i = 0 ; i < length ; i ++) {
3559
36- int prefixSum = getPrefixSumOfAnIndex (6 ,arrayList );
37- System .out .println ("Prefix Sum is " + prefixSum );
60+ int left = 0 ;
61+ if (i == 0 ){
62+ left = 0 ;
63+ }else {
64+ left = prefixArray .get (i -1 );
65+ }
66+ int right = prefixArray .get (length ) - prefixArray .get (i );
67+ if (left == right ){
68+ return i ;
69+ }
70+ }
71+
72+ return -1 ;
73+ }
74+
75+ static ArrayList <Integer > getPrefixSumArrayOfAnArray (ArrayList <Integer > list ){
76+
77+ ArrayList <Integer > prefixArrayList = new ArrayList <>();
78+
79+ for (int i = 0 ; i < list .size ()-1 ; i ++) {
80+
81+ prefixArrayList .add (getPrefixSumOfAnIndex (i ,list ));
82+ }
83+ return prefixArrayList ;
3884 }
85+
86+
3987}
0 commit comments