-
Notifications
You must be signed in to change notification settings - Fork 0
/
Equilibrium_index_of_an_array
34 lines (34 loc) · 1.4 KB
/
Equilibrium_index_of_an_array
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
/* Programmer : Dhruv Patel
* Problem Name : Equilibrium index of an array
* Used In : geeksforgeeks
* Used As : Practice_Question
* Problem :
* Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the
* sum of elements at higher indexes. For example, in an arrya A:
* A[0] = -7, A[1] = 1, A[2] = 5, A[3] = 2, A[4] = -4, A[5] = 3, A[6]=0
* 3 is an equilibrium index, because:
* A[0] + A[1] + A[2] = A[4] + A[5] + A[6]
* 6 is also an equilibrium index, because sum of zero elements is zero, i.e., A[0] + A[1] + A[2] + A[3] + A[4] + A[5]=0
* 7 is not an equilibrium index, because it is not a valid index of array A.
*
* Thoughts =>
* The following code uses two for loops. One goes in forward direction and nested on goes into backward direction
* which compare the sum with the outside loop if match found than prints the value of equilibrim index.
*/
class Equilibrium_index_of_an_array {
public static void main(String args[]){
int a [] = { -7, 1, 5, 2, -4, 3, 0};
int sum = 0;
int c_sum = 0;
for(int i = 0 ; i < a.length-1 ; i++) {
sum+=a[i];
for(int j = i+1 ; j < a.length ; j++) {
c_sum+=a[j];
if(sum==c_sum){
System.out.println(i+1);
}
}
c_sum=0;
}
}
}