Repository navigation
Expand file tree
/
Copy pathEquilibriumIndex.java
More file actions
89 lines (63 loc) · 2.07 KB
/
Copy pathEquilibriumIndex.java
File metadata and controls
89 lines (63 loc) · 2.07 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package Arrays;
import java.util.ArrayList;
public class EquilibriumIndex {
public static void main(String[] args) {
ArrayList<Integer> arrayList = new ArrayList<>(100);
arrayList.add(-7);
arrayList.add(1);
arrayList.add(5);
arrayList.add(2);
arrayList.add(-4);
arrayList.add(3);
arrayList.add(0);
// arrayList.add(-3);
// arrayList.add(6);
// arrayList.add(2);
// arrayList.add(4);
// arrayList.add(5);
// arrayList.add(-1);
// arrayList.add(2);
// arrayList.add(-3);
// arrayList.add(6);
// arrayList.add(2);
// arrayList.add(4);
// arrayList.add(5);
// arrayList.add(-1);
// arrayList.add(2);
int index = findEquilibriumIndex(arrayList);
System.out.println("Equilibrium Index is " + index);
}
static int getPrefixSumOfAnIndex(int index, ArrayList<Integer> arrayList){
int prefixSum = 0;
for (int i = 0; i <= index; i++) {
prefixSum = prefixSum + arrayList.get(i);
}
System.out.println(prefixSum);
return prefixSum;
}
static int findEquilibriumIndex(ArrayList<Integer> arrayList) {
ArrayList<Integer> prefixArray = getPrefixSumArrayOfAnArray(arrayList);
System.out.println(prefixArray);
int length = prefixArray.size()-1;
for (int i = 0; i < length; i++) {
int left = 0;
if (i == 0){
left = 0;
}else{
left = prefixArray.get(i -1);
}
int right = prefixArray.get(length) - prefixArray.get(i);
if (left == right){
return i;
}
}
return -1;
}
static ArrayList<Integer> getPrefixSumArrayOfAnArray(ArrayList<Integer> list){
ArrayList<Integer> prefixArrayList = new ArrayList<>();
for (int i = 0; i < list.size()-1; i++) {
prefixArrayList.add(getPrefixSumOfAnIndex(i,list));
}
return prefixArrayList;
}
}